SUBROUTINE emaxfun()
  USE commonvars
  IMPLICIT NONE
  INCLUDE 'mpif.h'

  REAL(8)              :: util, pcons, qcons, zzpuf, steal, newsav, newsavi, vemaxp, ability
  REAL(8)              :: t1, t2, wealthin
  INTEGER              :: t, imun, iedu, iedui, ia, isav, ifine, ipast, iwealth, ifu, ipr, ipau, jj, agen, agei, age, elap, &
                          ipasti, iwealthi, inewwealthi, iterm, itermi, ifup, iprp, voter_age, isteal, iq, agec, ieduc, iwealthc
  REAL(8), ALLOCATABLE :: ptempt_run(:,:,:,:,:,:,:,:,:), ptemp_run(:,:,:,:,:,:,:,:,:), &
                          ptemppmayor(:,:,:,:,:,:,:,:,:,:,:,:), ptemppmayort(:,:,:,:,:,:,:,:,:,:,:,:), &
                          newsavf(:,:,:,:,:,:,:,:,:), newsavft(:,:,:,:,:,:,:,:,:), qconsf(:,:,:,:,:,:,:,:,:), qconsft(:,:,:,:,:,:,:,:,:), &
                          utilt(:,:,:,:,:,:,:,:,:), utiltt(:,:,:,:,:,:,:,:,:), vemaxt(:,:,:,:,:,:,:,:,:), vemaxtt(:,:,:,:,:,:,:,:,:), &
                          vemax_voter_it(:,:,:,:,:,:,:,:,:,:,:,:), vemax_voter_i(:,:,:,:,:,:,:,:,:,:,:,:), vemax_voter_i_age(:,:,:,:,:,:,:,:,:,:,:,:,:,:), &
                          vemax_voter_ct(:,:,:,:,:), vemax_voter_c(:,:,:,:,:), vemax_voter_c_age(:,:,:,:,:,:,:), &
                          vemax_voter_ct_all(:,:,:,:,:,:,:,:), vemax_voter_c_all(:,:,:,:,:,:,:,:), vemax_voter_c_age_all(:,:,:,:,:,:,:,:,:,:), &
                          temp_prob_ct(:,:,:,:,:), temp_prob_c(:,:,:,:,:), temp_prob_ct_all(:,:,:,:,:,:,:,:), temp_prob_c_all(:,:,:,:,:,:,:,:), &
                          emax_est(:,:,:,:,:,:,:,:,:), emax_estt(:,:,:,:,:,:,:,:,:), emax_est_temp(:,:,:,:), emax_run_temp(:,:,:,:), &
                          emax_runt(:,:,:,:,:,:,:,:,:),emax_run(:,:,:,:,:,:,:,:,:), emax_not(:,:,:,:,:), &
                          emaxpmayor(:,:,:,:,:,:,:,:,:,:,:,:), emaxpmayornor(:,:,:,:,:), emaxpmayort(:,:,:,:,:,:,:,:,:,:,:,:), emaxpmayortemp1(:,:,:), &
                          emaxpmayortemp2(:,:,:,:), betanewrt(:,:,:,:,:,:), betanewrtt(:,:,:,:,:,:), &
                          betapmayort1(:,:,:,:,:,:,:,:,:,:),betapmayort2(:,:,:,:,:,:,:,:,:), betapmayortt1(:,:,:,:,:,:,:,:,:,:), betapmayortt2(:,:,:,:,:,:,:,:,:), &
                          betasimrunt(:,:,:,:,:,:), betasimruntt(:,:,:,:,:,:), ELNqconsout_i(:,:,:,:,:,:,:,:,:), ELNqconsout_i_1(:,:,:,:,:,:,:,:,:), &
                          temp_vfun(:), Pr_i_wint(:,:,:,:,:,:,:,:,:,:,:,:), Pr_i_wintt(:,:,:,:,:,:,:,:,:,:,:,:), pqtemp_it(:,:,:,:,:,:,:,:,:,:,:,:), &
                          pqtemp_i(:,:,:,:,:,:,:,:,:,:,:,:), pEqtemp_i(:,:,:,:,:,:,:,:,:), beta_voter_it(:,:,:,:,:,:,:,:), beta_voter_itt(:,:,:,:,:,:,:,:), &
                          vemax_voter_i_temp(:,:,:,:), vemax_voter_c_temp(:,:), beta_voter_ct(:,:,:,:,:,:), beta_voter_ctt(:,:,:,:,:,:), &
                          stealf(:,:,:,:,:,:,:,:,:), stealft(:,:,:,:,:,:,:,:,:), &
                          pr_runtt(:,:,:,:,:,:,:), pr_runt(:,:,:,:,:,:,:), pr_run(:,:,:,:,:,:,:,:,:), &
                          qconsout(:,:,:,:,:,:,:,:,:,:,:), stealout(:,:,:,:,:,:,:,:,:,:,:), newsavout(:,:,:,:,:,:,:,:,:,:,:)
!!$ELNqconsout_c(:,:), ELNqconsout_c_1(:,:)
!!$  INTEGER,ALLOCATABLE  :: runtt(:,:,:,:,:,:,:,:,:,:,:,:), runt(:,:,:,:,:,:,:,:,:,:,:,:), agemayor(:)
  INTEGER,ALLOCATABLE  :: agemayor(:)
  INTEGER              :: counter1, counter2, counter3, counter4, counter5, counter6, counter7, totfirstloop, totsecondloop, &
                          totthirdloop, totfourthloop, totfifthloop, totsixthloop, totseventhloop, ntasks1, ntasks2, ntasks3, ntasks4, ntasks5, ntasks6, &
                          ntasks7, restasks1, restasks2, restasks3, restasks4, restasks5, restasks6, restasks7, loop_vf1, ntasks_vf1, restasks_vf1, counter_vf1, &
                          loop_vf3, ntasks_vf3, restasks_vf3, counter_vf3, count_steal, count_q, nprocs_t, myrank_t
  REAL(8)              :: mwage, pmwage, fundsf, zzprf, wealthf, wage_pastmayor, min_util, upower_t, cost_run_frac_t, ELNqcons, qconsil, qconsi, fr_stolenit, &
                          popsizet, pp, Phi_arg, arg_exp, pnorm, vemax_voter_i_pp, vemax_voter_c_pp, alpha_nstt, alpha_eat, probage, probqcons_ct, probqcons_ct_all, &
                          newsteal, fine_fun, qconsvec_t(Nq), probqcons_it, av_qcons, diff_qcons, thres_count, av_res_temp(Nwealth), v_slope, v_slope_p
  
  EXTERNAL             :: prob_ic_emax, mayordecision, notmayordecision, probemax, vfunapprox_age, vfunapprox_age_q, vfunapprox_age_steal, vfunapprox_age_steal_q, &
                          vfunapprox_q, vfunapprox_steal, vfunapprox_steal_q, vfunapprox_ability, vfunapprox_ability_q, vfunapprox_ability_steal, vfunapprox_ability_steal_q, pnorm, fine_fun
  
  ! We run two loops:
  ! the first is needed to compute the public consumption for individuals that are not mayors
  ! the second generates the actual value functions

  
!!$  nprocs = 1

  IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
     nprocs_t = nprocs
     myrank_t = myrank
  ELSE
     nprocs_t = nprocs_new
     myrank_t = my_new_comm_rank
  END IF

  ALLOCATE(qconsout(Tend,Nmun,Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
       stealout(Tend,Nmun,Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
       newsavout(Tend,Nmun,Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc))
  qconsout = 0d0
  stealout = 0d0
  newsavout = 0d0

  !threshold to count different emaxs for vfunapprox
  thres_count = 0.0000001d0

  DO jj = 1, 2

     !The following reals are only used in the simulation of the municipalities
     mwage = 0d0
     wealthf = 0d0
     fundsf = 0d0
     zzprf = 0d0
     util = 0d0
     qcons = 0d0
     newsav = 0d0
     inf_bound_pm = -infty
     inf_bound_pmg = -infty
     inf_bound_pmgp1 = -infty
     
     ALLOCATE(Pr_i_win(Nmun,Tend,Npast,Neduc,Nwealth,Npaudits,Nnterms,Nsteal,Nq,Nelap,Tend,Neduc,Nwealth))
     Pr_i_win = 0d0
     
     ALLOCATE(vemax_voter_i_age(Tend,Nmun,Nnterms,4,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
     ALLOCATE(vemax_voter_c_age(Tend,Nmun,Nelap,Npast_t,Nwealth,Npaudits,Neduc), vemax_voter_c_age_all(Tend,Nmun,4,Nwealth,Neduc,Nelap,Npast_t,Nwealth,Npaudits,Neduc))
     vemax_voter_i_age = 0d0
     vemax_voter_c_age = 0d0
     vemax_voter_c_age_all = 0d0

!!$     ALLOCATE(runtt(Tend,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc), runt(Tend,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc,Npr))
!!$     runtt = 0; runt = 0
     ALLOCATE(pr_run(Tend,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq))
     pr_run = 0d0
     
     !The following loop constructs the value function for an individual who 
     !is, was in the last period, or was two periods or more ago a mayor
     
     !The emax is composed of 4 parts.
     !1. Compute the value of an individual who is a mayor this period;
     !2. Compute the value of an individual who was a mayor the previous period (lost the election this period);
     !3. Compute the value of an individual who was a mayor two periods or more ago 
     !and lives in a period in which the election this period is won by the incumbent
     !4. Compute the value of an individual who was a mayor two periods or more ago 
     !and lives in a period in which the election this period is won by the challenger
     
     !! New part: Retirement
     ! 1. Changes in year previous  to retirement (not allowed to run next period) -> changes in part 1.
     ! 2. Changes in year of retirement (past mayor the previous period)
     ! 3. Changes in years following retirement year (mayor two periods or more ago)
     
     !Challengers are chosen randomly from the population
     
     !Note that emax and emaxpmayor depend on time, municipality, and education (they are state variables)
     !But we don't consider them in the arrays because we only need to save the parameters of the approximated value function
     
     !time period
     DO t = Tend,1,-1

        IF(t == Tend) flag_Tend = 1
        
        IF (jj == 1) THEN
           
           IF (t == 10) THEN
              agen = 1
              ALLOCATE(agemayor(agen))
              agemayor = (/ 10 /)
           ELSE IF(t == 9) THEN
              agen = 1
              ALLOCATE(agemayor(agen))
              agemayor = (/ 9 /)
           ELSE IF(t == 8) THEN
              agen = 3
              agemayor = (/ 8, 9, 10 /)
           ELSE IF(t == 7) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 7, 8, 9 /)
           ELSE IF(t == 6) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 6, 7, 8 /)
           ELSE IF(t == 5) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 5, 6, 7 /)
           ELSE IF(t == 4) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 4, 6, 7 /)
           ELSE IF(t == 3) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 3, 4, 6 /)
           ELSE IF(t == 2) THEN
              agen = 3
              ALLOCATE(agemayor(agen))
              agemayor = (/ 2, 4, 6 /)
           ELSE IF(t == 1) THEN
              agemayor = (/ 1, 3, 5 /)
           END IF

        ELSE
           
           agen = 4
           ALLOCATE(agemayor(agen))           
           agemayor = (/ 1, 3, 5, 7 /)

        END IF

        ! This is used in the computation of vemax_voter_c
        probage=(1d0/DBLE(ageN))
        
        !Compute the size of all loop
        totfirstloop = Neduc*Nab*Npaudits*Nwealth*Nfunds*Npr*Nnterms
        totsecondloop = Neduc*Npaudits*Nwealth*Npast_t*Nelap*Nwealth*Neduc*Npast*agen
        totthirdloop = Neduc*Npaudits*Nwealth*Npast_t*Nelap*Nwealth
        totfourthloop = Npaudits*Nwealth*Neduc*Npast*agen
        totfifthloop = Neduc*Nab*Npaudits*Nwealth*Nfunds*Npr*(Nnterms-1)*Npast
        totsixthloop = Neduc*Npaudits*Nwealth*Nelap*Nwealth*Neduc*agen
        totseventhloop = Neduc*Nab*Npaudits*Nwealth*(Nnterms-1)*Npast*Nelap

        !Compute the numnber of tasks to assign to each processor
        ntasks1 = INT(totfirstloop/nprocs_t)
        restasks1 = totfirstloop - ntasks1*nprocs_t
        ntasks2 = INT(totsecondloop/nprocs_t)
        restasks2 = totsecondloop - ntasks2*nprocs_t
        ntasks3 = INT(totthirdloop/nprocs_t)
        restasks3 = totthirdloop - ntasks3*nprocs_t
        ntasks4 = INT(totfourthloop/nprocs_t)
        restasks4 = totfourthloop - ntasks4*nprocs_t
        ntasks5 = INT(totfifthloop/nprocs_t)
        restasks5 = totfifthloop - ntasks5*nprocs_t
        ntasks6 = INT(totsixthloop/nprocs_t)
        restasks6 = totsixthloop - ntasks6*nprocs_t
        ntasks7 = INT(totseventhloop/nprocs_t)
        restasks7 = totseventhloop - ntasks7*nprocs_t

        CALL cpu_time(t1)

        !municipality
        DO imun = 1, Nmun
           popsizeg = popsize(imun)
           ! This global variable is used in all vfunapprox subroutines
           qconsvec_g(:) = LOG(qconsvec(imun,:))
           ! This local variabel is used in the updating of theta and ability probabilities; we use the log of qcons in levels to have it positive
!!$           qconsvec_t(:) = qconsvec(imun,:)+LOG(popsize(imun))
           qconsvec_t(:) = qconsvec_g(:)
           subqcons = subqcons_vec(imun)
!!$           if (myrank_t == 0) write(*,'(a,3f20.10)') 'qconsvec_g', qconsvec_g(:)
!!$           if (myrank_t == 0) write(*,'(a,3f20.10)') 'qconsvec_t', qconsvec_t(:)
           
           !The wage of the mayor is a deterministic function of the municipality s/he belongs to
           mwage = wage_mayor(imun)
           ALLOCATE(emax_runt(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq))
           ALLOCATE(ptempt_run(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq))
           ALLOCATE(utilt(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), utiltt(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc))
           
           emax_runt = 0d0        
           ptempt_run = 0d0
           utilt = 0d0
           utiltt = 0d0

           ALLOCATE(qconsft(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                stealft(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                newsavft(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                qconsf(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                stealf(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                newsavf(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                vemaxt(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                vemaxtt(Nelap,Nnterms,Npr,Nfunds,Nwealth,Npaudits,Nfines,Nab,Neduc), &
                betanewrt(Npast,Nnterms,Npaudits,Neduc,Nelap,MMability_steal_q), betanewrtt(Npast,Nnterms,Npaudits,Neduc,Nelap,MMability_steal_q))
           
           ! Intitializing decision arrays (outside time loop)
           qconsf = 0d0
           stealf = 0d0
           newsavf = 0d0
           qconsft = 0d0
           stealft = 0d0
           newsavft = 0d0
           vemaxt = 0d0
           vemaxtt = 0d0
           betanewrt = 0d0
           betanewrtt = 0d0
                
           IF (jj == 1 .AND. t == Tend) THEN
              upower_t = upower
              cost_run_frac_t = cost_run_frac
           ELSE IF (t < Tend) THEN
              upower_t = upower*ABS(av_util_mayors_g(imun,t+1))
              cost_run_frac_t = cost_run_frac*ABS(av_util_mayors_g(imun,t+1))
           ELSE IF (jj == 2 .AND. t == Tend) THEN
              upower_t = upower*ABS(av_util_mayors_g(imun,t))
              cost_run_frac_t = cost_run_frac*ABS(av_util_mayors_g(imun,t))
           END IF
           
           IF (jj == 2) THEN
              IF (t >= Retage) THEN 
                 GO TO 9934
              END IF
           END IF
           
           !1. Compute the value of an individual who is a mayor this period;
           !We consider first the case of an incumbent who was reelected
           counter1 = 0
           ! We don't need the variable ifine; at the right time we should get rid of it in the arrays
           ifine = 1
           !education of the individual
           DO iedu = 1, Neduc
              !This variable describes the type of mayor:
              DO ia = 1, Nab
                 ability = a_discr(ia)
                 !The probability of being audit may differ across terms
                 DO ipau = 1, Npaudits
                    paudit_g = paudit(0,ipau)
                    
                    !CURRENT VARIABLES
                    !savings
                    DO iwealth = 1, Nwealth
                       !funds received by the municipality (not the incumbent) from central goverment
                       DO ifu = 1, Nfunds
                          !private inputs in the production function for public consumption
                          DO ipr = 1, Npr
                             !We cannot start from iterm = 2 even if iterm = 1 only for a challenger 
                             !who was elected, because we need qq, etc producted also by a winning challenger
                             DO iterm = 1, Nnterms
                                ! paudit_g is used in mayorsolution0.f90 and mayorsolution.f90 to account for the probability of being audited the next term
                                IF (flag_audit_nterm == 1 .AND. iterm == Nnterms) THEN
                                   paudit_g = paudit_nterm(0)
                                ELSE
                                   paudit_g = paudit(0,ipau)
                                END IF
                                
                                counter1 = counter1 + 1
                                IF ((counter1 <= ntasks1*nprocs_t .AND. counter1 >= myrank_t*ntasks1+1 .AND. counter1 <= myrank_t*ntasks1+ntasks1) .OR. &
                                     (counter1 > ntasks1*nprocs_t .AND. counter1 - ntasks1*nprocs_t - 1 == myrank_t)) THEN
                                   
                                   DO elap = 1, Nelap
                                      
                                      IF (t < Tend) THEN
                                         IF (iterm < Nnterms) THEN
                                            ALLOCATE(betat1(MMability_steal_q),betat2(MMability_steal_q))
                                            !inside mayorsolution.f90 we need the betas for t+1 for mayors with different types of stealing behavior the current period
                                            IF (Npast > 1) THEN
                                               betat1(:) = betanewcr(t+1,imun,1,iterm+1,ipau,iedu,elap,:)
                                               betat2(:) = betanewcr(t+1,imun,2,iterm+1,ipau,iedu,elap,:)
                                               IF (flag_no_run == 1 .OR. flag_norun_prob_policy == 1) THEN
                                                  ALLOCATE(betat3(Nwealth))
                                                  betat3(:) = betanornew(t+1,imun,2,ipau,iedu,elap,:)
                                               END IF
                                            ELSE
                                               betat1(:) = betanewcr(t+1,imun,1,iterm+1,ipau,iedu,elap,:)
                                            END IF
                                            MMg = MMability_steal_q
                                         ELSE
                                            ALLOCATE(betat1(Nwealth),betat2(Nwealth))
                                            !If they cannot run, it is indifferent whether they steal in the current period
                                            IF (Npast > 1) THEN
                                               betat1(:) = betanornew(t+1,imun,1,ipau,iedu,elap,:)
                                               betat2(:) = betanornew(t+1,imun,2,ipau,iedu,elap,:)
                                            ELSE
                                               betat1(:) = betanornew(t+1,imun,1,ipau,iedu,elap,:)
                                            END IF
                                            MMg = Nwealth
                                         END IF
                                                                                        
                                      END IF
                                      
                                      !Here we determine the optimal decisions of the incumbent if reelected
                                      ! Change here required, no more t=Tend, just mayordecision and change mayordecision
                                      CALL mayordecision(t,imun,iedu,ability,ipau,mwage,iwealth,wealthf,ifu,fundsf,ipr,zzprf,iterm,pcons,qcons,zzpuf,newsav,steal,util,vemaxp)
                                      
                                      IF (t < Tend) THEN
                                         
                                         ! WE SAVE THE VALUE FUNCTION SO THAT WE DON'T HAVE TO RECOMPUTE EVERYTHING IN MAYORDECISION LATER IN THE CODE
                                         !the amount of public good produced by the incumbent in the previous period affects 
                                         !today's probability of being elected, but not current decisions (qcons, etc)
                                         !because those decisions are made after the mayor has been elected
                                         !the same is true for isx
                                         !current qcons affects all other decisions
                                         !the relative contributions affect the probability of being elected, 
                                         !but not the utility. We can therefore integrate them out
                                         
                                         !We add upower as a fraction of the average value of the mayors' utility
                                         !We subtract the utility cost of running if the mayor was audited and stole (ipast = 3)
!!$                                            vemaxtt(elap,ipast,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu,isteal,ifinel) = vemaxp + upower_t !+ upower !ABS(vemaxp)*upower
                                         vemaxtt(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = vemaxp + upower !ABS(util)*upower !ABS(vemaxp)*upower
                                         DEALLOCATE(betat1,betat2)
                                         IF ((flag_no_run == 1 .OR. flag_norun_prob_policy == 1) .AND. iterm < Nnterms) DEALLOCATE(betat3)
                                                                                     
                                      END IF
                                         
                                      !We save the utility to compute upower_t and cost_run_t as a fraction of the average utility
                                      !iq does not affect decisions only because we are assuming that 
                                      !there is no interaction between iq, is, and ipast i
!!$                                         utiltt(elap,ipast,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu,isteal,ifinel) = util + upower_t !+ upower !ABS(util)*upower
                                      utiltt(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = util + upower ! + ABS(util)*upower
                                      
                                      !qcons DOES NOT take into account the degree of rivalry, we have to transform it in 
                                      !qcons = qcons/popsize**eta
                                      !Also, qcons doesn't depend on iq, because iq affects only the previous elections
                                      !and qcons is produced conditional on being elected
                                      qconsft(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = qcons/(popsizeg**eta)
                                      IF (t >= Tend .AND. qcons/((popsizeg)**eta) <= subqcons) THEN
                                         qconsft(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = subqcons+small_no
                                      END IF
                                      stealft(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = steal
                                      newsavft(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) = newsav
                                                                               
                                      flag_here = 0
                                                                                         
                                   END DO
                                   
                                END IF
                                   
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
              
              CALL MPI_ALLREDUCE(qconsft(1,1,1,1,1,1,1,1,1), qconsf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(stealft(1,1,1,1,1,1,1,1,1), stealf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(newsavft(1,1,1,1,1,1,1,1,1), newsavf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(vemaxtt(1,1,1,1,1,1,1,1,1), vemaxt(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(utiltt(1,1,1,1,1,1,1,1,1), utilt(1,1,1,1,1,1,1,1,1), Neduc*Nab*Nwealth*Nnterms*Npaudits*Nelap*Nfines*Npr*Nfunds, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)

              CALL MPI_ALLREDUCE(qconsft(1,1,1,1,1,1,1,1,1), qconsf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(stealft(1,1,1,1,1,1,1,1,1), stealf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(newsavft(1,1,1,1,1,1,1,1,1), newsavf(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(vemaxtt(1,1,1,1,1,1,1,1,1), vemaxt(1,1,1,1,1,1,1,1,1), Neduc*Nwealth*Nab*Nfines*Npr*Nfunds*Npaudits*Nnterms*Nelap, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(utiltt(1,1,1,1,1,1,1,1,1), utilt(1,1,1,1,1,1,1,1,1), Neduc*Nab*Nwealth*Nnterms*Npaudits*Nelap*Nfines*Npr*Nfunds, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

           END IF
           DEALLOCATE(qconsft, stealft, newsavft, vemaxtt, utiltt)
           
           ! We compute min_util, which is used to impute utility in the last period if the actual utility is < -infty
           IF (jj == 1 .AND. t >= Tend) THEN

              min_util = subutil(Tend)
              if (myrank_t == 0 .AND. flag_policy_evaluation == 0) write(*,*) 'min_util 1', min_util

           END IF

           av_util_mayors_g(imun,t) = 1d0
                      
!!$           CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)

           ! WE COMPUTE THE VALUE FUNCTIONS OF VOTERS IF AN INCUMBENT OR A CHALLENGER IS ELECTED
           
           ! Feeding the period t decisions into an array holding all periods(t=1:Tend,.....)        
           DO iedu = 1, Neduc
              DO ia = 1, Nab
                 DO ipau = 1, Npaudits
                    DO iwealth = 1, Nwealth
                       DO ifu = 1, Nfunds
                          DO ipr = 1, Npr
                             DO iterm = 1, Nnterms
                                DO elap = 1, Nelap

                                   ! We don't need ifine
                                   IF (qconsf(elap,iterm,ipr,ifu,iwealth,ipau,1,ia,iedu) <= subqcons) THEN
                                      qconsout(t,imun,elap,iterm,ipr,ifu,iwealth,ipau,:,ia,iedu) = subqcons
                                   ELSE
                                      qconsout(t,imun,elap,iterm,ipr,ifu,iwealth,ipau,:,ia,iedu) = qconsf(elap,iterm,ipr,ifu,iwealth,ipau,1,ia,iedu)
                                   END IF
                                   stealout(t,imun,elap,iterm,ipr,ifu,iwealth,ipau,:,ia,iedu) = stealf(elap,iterm,ipr,ifu,iwealth,ipau,1,ia,iedu)
                                   newsavout(t,imun,elap,iterm,ipr,ifu,iwealth,ipau,:,ia,iedu) = newsavf(elap,iterm,ipr,ifu,iwealth,ipau,1,ia,iedu)

                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           
           !We compute the probabilities that a challenger or incumbent is the current mayor
9934       IF (t >= Retage .AND. jj == 2) DEALLOCATE(qconsft, stealft, newsavft, vemaxtt, utiltt)

           CALL prob_ic_emax(agen)

           ! We compute the E[ln Q] if the current incumbent is elected
           ! We can compute E[ln Q] separately from the rest of the value function because E[ln Q] is additive in the utility function
           ! The expectation is taken over variables that will be realized during the next term and influence the production of Q
           ALLOCATE(ELNqconsout_i(agen,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq), ELNqconsout_i_1(agen,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq), &
                    pEqtemp_i(agen,Nmun,Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           ELNqconsout_i = 0d0
           ELNqconsout_i_1 = 0d0
           pEqtemp_i = 0d0
           
           ! Feeding the period t decisions into an array holding all periods(t=1:Tend,.....)
           ! We should compute the expectation of ELNqconsout_i using all the variables that are unknown to the voter (ability and theta) and the shocks (ipr, ifu, ifine, ... )
           ! VARIABLES KNOWN BY THE VOTER
           DO iedu = 1, Neduc
              DO ipau = 1, Npaudits
                 DO iwealth = 1, Nwealth
                    !We compute the average public consumption of a first term mayor to compare it with the public consumption of the incumbent
                    !Here iterm = 1 because we want to compute the average for potential challengers
                    av_qcons_vec(t,imun,ipau) = SUM(qconsout(t,imun,:,1,:,:,:,ipau,:,:,:))/DBLE(Nelap*Npr*Nfunds*Nfines*Nab*Nwealth*Neduc)
                    av_qcons = av_qcons_vec(t,imun,ipau)
                    ! Public consumptino in the previous period
                    DO iq = 1, Nq
                       ! Mayor's public consumptin in the previous term (iterm-1) to update pr_theta and mu_a
                       ! qconsvrc_g is already log or per-capita public consumption
                       qconsil = qconsvec_t(iq)
!!$                       diff_qcons = qconsvec_t(iq) - LOG(av_qcons)
!!$                       diff_qcons = qconsvec_t(iq)
                       ! qconsvec(imun,2) is average per capita public consumption in municipality imun in the data
                       diff_qcons = qconsvec_t(iq) - LOG(qconsvec(imun,2))

                       DO ipast = 1, Npast
                          ! Stealing in the previous period
                          DO isteal = 1, Nsteal
                             ! Mayor's stealing in the previous term (iterm-1) to update pr_theta and mu_a
                             fr_stolenit = fr_stoleni(isteal)
                             
                             ! Observed variables
                             ! A winning incumbent must be in iterm >= 2, but we also need the production of public consumption by a challenger
                             DO iterm = 1, Nnterms
                                DO age = 1, agen

                                   ! VARIABLES NOT KNOWN BY THE VOTER
                                   DO ia = 1, Nab
                                      ! We don't need ifine
                                      ifine = 1
                                      DO ifu = 1, Nfunds
                                         DO ipr = 1, Npr
                                            DO elap = 1, Nelap
                                               
                                               ! We have two indeces for the fine, one for the fine for stealing in the previous term and one for the next term; both are assumed to be unobserved
                                               probqcons_it = SUM(nonpardist_wealth_fu_pr(:,ifu,ipr)*pability(ia)*pappeal(elap))
                                                  
                                               ! To compute expected qcons, newsav, and stealing, we need variabels in this term
                                               qconsi = qconsout(agemayor(age),imun,elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu)
                                                  
                                               ! We transformed qcons in qcons = qcons/popsize**eta at L343 to account for the degree of rivalry
                                               IF (ABS(delta-1d0) < small_no) THEN
                                                  ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) = ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) + LOG(qconsi)*probqcons_it
                                               ELSE   
                                                  ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) = ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) + (qconsi**(1d0-delta)/(1d0-delta))*probqcons_it
                                               END IF
                                               ELNqconsout_i_1(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) = ELNqconsout_i_1(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) + LOG(qconsi)*probqcons_it
                                               
                                               pEqtemp_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) = pEqtemp_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) + probqcons_it
                                               
                                               IF (ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) <  check_bignumber) THEN                                            
                                                  write(*,'(a,10i5,3f20.10)') 'big ELNqcons_i 1ST', age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq, ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq), qconsout(agemayor(age),imun,elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu), probqcons_it
                                               END IF
                                               
!!$                                                  if (myrank_t == 0 .AND. t == 10 .AND. iterm==2 .AND. age==1 .AND. ipast==1 .AND. iedu==1 .AND. iwealth==1 .AND. ipau==1 .AND. isteal==1 .AND. iq==1) write(*,'(a,14i5,6f20.10)') 'ELNqcons', age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq,ia,ifine,ifu,ipr,elap,qconsi,(qconsi**(1d0-delta)/(1d0-delta)),LOG(qconsi),probqcons_it,ELNqconsout_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq),ELNqconsout_i_1(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq)
                                               
                                                  
                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                   
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           ifine = 1
           DO iedu = 1, Neduc
              DO ipau = 1, Npaudits
                 DO iwealth = 1, Nwealth
                    DO iterm = 1, Nnterms
                       DO ipast = 1, Npast
                          DO age = 1, agen
                             DO isteal = 1, Nsteal
                                DO iq = 1, Nq
                                   IF (pEqtemp_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) < 0.99d0 .OR. pEqtemp_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq) > 1.001d0) THEN
                                      IF (myrank_t == 0) WRITE(*,*) 'wrong prob qcons_i', pEqtemp_i(age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq),t,age,imun,ipast,iterm,iwealth,ipau,iedu,isteal,iq
                                   END IF
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           DEALLOCATE(pEqtemp_i)
           
           !2. Compute the value function of a voter if the election this period is won by the incumbent  
           ! In vemax_voter_it we store the value function of voters for different incumbents
           ALLOCATE(vemax_voter_it(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq), vemax_voter_i(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           vemax_voter_it = 0d0
           vemax_voter_i = 0d0
           
           IF (Nnterms <= 2) THEN
           
              counter2 = 0
              DO iedu = 1, Neduc                      
                 !The probability of being audited may differ across terms
                 DO ipau = 1, Npaudits
                    paudit_g = paudit(0,ipau)
                    
                    !Net Wealth
                    DO iwealth = 1, Nwealth
                       wealthin = wealth(iwealth)
                       ! The last value for ipast are need to compute the value function of voters as they have different average wages
                       ! ipast = 1 for the past mayor, ipast = 2 for the voter
                       ! We only need ipast=1 for past mayors because wages do not depend on ipast
                       DO ipast = 1, Npast_t
                          IF (ipast < Npast_t) THEN
                             pmwage = wage_pastmayor(t,imun,iedu,ipast)
                          ELSE
                             pmwage = wage_vot(imun)
                          END IF
                          ! electoral appeal of the incumbent
                          DO elap = 1, Nelap
                             
                             !The following variables belong to the current incumbent and not the past mayor we consider
                             !They are important because they determine the expected utility of public consumption produced by the challenger
                             !Those variables are state variables to determine that object
                             !Past history of this mayor: ipast is about what happened in all periods
                             DO iwealthi = 1, Nwealth
                                DO iedui = 1, Neduc
                                   DO ipasti = 1, Npast
                                      past_g = 0d0
                                      IF (ipasti == 2) past_g = 1d0
                                      DO agei = 1, agen
                                         agemayort = agemayor(agei)
                                         
                                         counter2 = counter2 + 1
                                         IF ((counter2 <= ntasks2*nprocs_t .AND. counter2 >= myrank_t*ntasks2+1 .AND. counter2 <= myrank_t*ntasks2+ntasks2) .OR. &
                                              (counter2 > ntasks2*nprocs_t .AND. counter2 - ntasks2*nprocs_t - 1 == myrank_t)) THEN
                                            
                                            ! The incumbent must be in term > 1
                                            DO itermi = 2, Nnterms
                                               itermi_g = itermi
                                               ! paudit_g is used in pastmayorsolution.f90 to account for the probability of being audited the next term
                                               IF (flag_audit_nterm == 1 .AND. itermi == Nnterms) THEN
                                                  paudit_g = paudit_nterm(0)
                                               ELSE
                                                  paudit_g = paudit(0,ipau)
                                               END IF
                                               
                                               ! Public consumption in the previous period is used to update the probability of ability and hence expected public consumption this period
                                               DO iq = 1, Nq
                                                  
                                                  ! Incumbent's past stealing and fine, this is relevant only if iterm == 2 and ipast == 2 (audited)
                                                  DO isteal = 1, Nsteal
                                                     IF ((iterm == 1 .OR. ipasti == 1) .AND. isteal > 1) CYCLE

                                                     !We read in the expected utility of public consumption produced by the incumbent above
                                                     ! This is used inside the utility function of the non-mayor individual E(qcons**(1-delta)/(1-delta))
                                                     ELNqcons = ELNqconsout_i(agei,imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
                                                     ! This is used as an input in the value function E(log(qcons))
                                                     ELNqcons_g = ELNqconsout_i_1(agei,imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
                                                                                                          
                                                     IF (t < Tend) THEN
                                                        ALLOCATE(betat1(Nwealth), betat2(Nwealth))
                                                        MMg = Nwealth
                                                        betat1(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                        betat2(:) = betat1(:)
                                                     END IF
                                                              
                                                     !Here we determine the optimal decisions of the incumbent if not reelected 
                                                     !This subroutine produces as output the global variables: vemaxoptpmg, pconsoptpmg, qconsoptpmg, newsavoptpmg, utiloptpmg, emaxoptpmg, obtained in pastmayorsolution.f90                                                     
                                                     CALL notmayordecision(t,pmwage,wealthin,ELNqcons)

!!$                                                     IF (jj == 2 .AND. T == Tend) write(*,'(a,12i5,2f20.10)') 'ELNqcons 1', itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq,ELNqcons,utiloptpmg
                                                     
                                                     IF (t >= Tend) THEN
                                                        
                                                        IF (utiloptpmg > -check_infty) THEN
                                                           
                                                           vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = utiloptpmg
                                                           
                                                        ELSE
                                                           
                                                           vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = min_util-per_min_util*ABS(min_util)
                                                           
                                                        END IF
                                                        
                                                     ELSE
                                                        
                                                        vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = vemaxoptpmg
                                                        
                                                     END IF
                                                     
                                                     IF (t < Tend) DEALLOCATE(betat1,betat2)
                                                     IF (ALLOCATED(betat3)) DEALLOCATE(betat3)
                                                              
                                                  END DO
                                               END DO
                                            END DO
                                            
                                         END IF
                                         
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

           ELSE
              
              ALLOCATE(pqtemp_it(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq), pqtemp_i(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
              
              pqtemp_it = 0d0
              pqtemp_i = 0d0
              
              counter2 = 0
              DO iedu = 1, Neduc                      
                 !The probability of being audited may differ across terms
                 DO ipau = 1, Npaudits
                    paudit_g = paudit(0,ipau)
                    
                    !Net Wealth
                    DO iwealth = 1, Nwealth
                       wealthin = wealth(iwealth)
                       ! The last value for ipast are need to compute the value function of voters as they have different average wages
                       ! ipast = 1 for the past mayor, ipast = 2 for the voter
                       ! We only need ipast=1 for past mayors because wages do not depend on ipast
                       DO ipast = 1, Npast_t
                          IF (ipast < Npast_t) THEN
                             pmwage = wage_pastmayor(t,imun,iedu,ipast)
                          ELSE
                             pmwage = wage_vot(imun)
                          END IF
                          ! electoral appeal of the incumbent
                          DO elap = 1, Nelap
                             
                             !The following variables belong to the current incumbent and not the past mayor we consider
                             !They are important because they determine the expected utility of public consumption produced by the challenger
                             !Those variables are state variables to determine that object
                             !Past history of this mayor: ipast is about what happened in all periods
                             DO iwealthi = 1, Nwealth
                                DO iedui = 1, Neduc
                                   DO ipasti = 1, Npast
                                      past_g = 0d0
                                      IF (ipasti == 2) past_g = 1d0
                                      DO agei = 1, agen
                                         agemayort = agemayor(agei)
                                         
                                         counter2 = counter2 + 1
                                         IF ((counter2 <= ntasks2*nprocs_t .AND. counter2 >= myrank_t*ntasks2+1 .AND. counter2 <= myrank_t*ntasks2+ntasks2) .OR. &
                                              (counter2 > ntasks2*nprocs_t .AND. counter2 - ntasks2*nprocs_t - 1 == myrank_t)) THEN
                                            
                                            ! The incumbent must be in term > 1
                                            DO itermi = 2, Nnterms
                                               itermi_g = itermi
                                               ! paudit_g is used in pastmayorsolution.f90 to account for the probability of being audited the next term
                                               IF (flag_audit_nterm == 1 .AND. itermi == Nnterms) THEN
                                                  paudit_g = paudit_nterm(0)
                                               ELSE
                                                  paudit_g = paudit(0,ipau)
                                               END IF
                                               
                                               ! Public consumption in the previous period is used to update the probability of ability and hence expected public consumption this period
                                               DO iq = 1, Nq
                                                  
                                                  ! Incumbent's past stealing and fine, this is relevant only if iterm == 2 and ipast == 2 (audited)
                                                  DO isteal = 1, Nsteal
                                                     IF ((itermi == 1 .OR. ipasti == 1) .AND. isteal > 1) CYCLE
                                                     
                                                     DO ia = 1, Nab
                                                        ! We don't need ifine
                                                        ifine = 1
                                                        DO ifu = 1, Nfunds
                                                           DO ipr = 1, Npr
                                                              
                                                              qconsi = qconsout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)
                                                              newsteal = stealout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)
                                                              new_fr_stolen_g = newsteal/funds(ifu)
                                                              newsavi = newsavout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)
                                                                 
                                                              !We read in the expected utility of public consumption produced by the incumbent above
                                                              ! This is used inside the utility function of the non-mayor individual E(qcons**(1-delta)/(1-delta))
                                                              IF (ABS(delta-1d0) < small_no) THEN
                                                                 ELNqcons = LOG(qconsi)
                                                              ELSE
                                                                 ELNqcons = (qconsi**(1d0-delta)/(1d0-delta))
                                                              END IF
                                                              ! This is used as an input in the value function E(log(qcons))
                                                              ELNqcons_g = LOG(qconsi)
                                                              
                                                              inewwealthi=0
                                                              IF(newsavi < (wealth(2)+wealth(1))/2d0) THEN
                                                                 inewwealthi=1
                                                                 GO TO 433
                                                              END IF
                                                              DO isav = 2, Nwealth-1
                                                                 IF(newsavi >= (wealth(isav)+wealth(isav-1))/2d0 .AND. newsavi < (wealth(isav+1)+wealth(isav))/2d0) THEN
                                                                    inewwealthi=isav
                                                                    GO TO 433
                                                                 END IF
                                                              END DO
                                                              IF(newsavi >=(wealth(Nwealth)+wealth(Nwealth-1))/2d0) THEN
                                                                 inewwealthi = Nwealth
                                                              END IF
433                                                           IF(inewwealthi==0) WRITE(*,*) 'Wrong beta assignmentL2,inewwealthi',inewwealthi,newsavi
                                                                                                                                  
                                                              IF (t < Tend) THEN
                                                                 IF (jj == 1 .AND. t >= 5) THEN  
                                                                    IF (itermi < Nnterms .AND. agemayor(agei) < MIN(Tend-1,Retage-1)) THEN
                                                                       ALLOCATE(betat1(MMsteal_q), betat2(MMsteal_q))
                                                                       MMg = MMsteal_q
                                                                       betat1(:) = betapmayortemp1(t+1,imun,itermi+1,agemayor(agei),1,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                                       betat2(:) = betapmayortemp1(t+1,imun,itermi+1,agemayor(agei),2,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                                       IF (flag_no_run == 1 .OR. flag_norun_prob_policy == 1) THEN
                                                                          ALLOCATE(betat3(Nwealth))
                                                                          betat3(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                                       END IF
                                                                    ELSE IF (itermi >= Nnterms .OR. agemayor(agei) >= MIN(Tend-1,Retage-1)) THEN
                                                                       ALLOCATE(betat1(Nwealth), betat2(Nwealth))
                                                                       MMg = Nwealth
                                                                       betat1(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                                       betat2(:) = betat1(:)
                                                                    END IF
                                                                 ELSE
                                                                    IF (itermi < Nnterms .AND. agemayor(agei) < Retage-1) THEN
                                                                       ALLOCATE(betat1(MMage_steal_q), betat2(MMage_steal_q))
                                                                       MMg = MMage_steal_q
                                                                       betat1(:) = betapmayor(t+1,imun,itermi+1,1,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                                       betat2(:) = betapmayor(t+1,imun,itermi+1,2,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                                       IF (flag_no_run == 1 .OR. flag_norun_prob_policy == 1) THEN
                                                                          ALLOCATE(betat3(Nwealth))
                                                                          betat3(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                                       END IF
                                                                    ELSE IF (itermi >= Nnterms .OR. agemayor(agei) >= Retage -1) THEN
                                                                       ALLOCATE(betat1(Nwealth), betat2(Nwealth))
                                                                       MMg = Nwealth
                                                                       betat1(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                                       betat2(:) = betat1(:)
                                                                    END IF
                                                                 END IF
                                                              END IF
                                                              
                                                              !Here we determine the optimal decisions of the incumbent if not reelected 
                                                              !This subroutine produces as output the global variables: vemaxoptpmg, pconsoptpmg, qconsoptpmg, newsavoptpmg, utiloptpmg, emaxoptpmg, obtained in pastmayorsolution.f90
                                                              CALL notmayordecision(t,pmwage,wealthin,ELNqcons)               
                                                              
                                                              probqcons_it = SUM(nonpardist_wealth_fu_pr(:,ifu,ipr)*pability(ia))
                                                              
                                                              IF (t >= Tend) THEN
                                                                 
                                                                 IF (utiloptpmg > -check_infty) THEN
                                                                    
                                                                    vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + utiloptpmg*probqcons_it
                                                                    
                                                                 ELSE
                                                                    
                                                                    vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + (min_util-per_min_util*ABS(min_util))*probqcons_it
                                                                    
                                                                 END IF
                                                                 
                                                              ELSE
                                                                 
                                                                 vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = vemax_voter_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + vemaxoptpmg*probqcons_it
                                                                 
                                                              END IF
                                                              
                                                              IF (t < Tend) DEALLOCATE(betat1,betat2)
                                                              IF (ALLOCATED(betat3)) DEALLOCATE(betat3)
                                                              
                                                              pqtemp_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = pqtemp_it(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + probqcons_it
                                                              
                                                           END DO
                                                        END DO
                                                     END DO
                                                  END DO
                                               END DO
                                            END DO
                                            
                                         END IF
                                         
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)              
                 CALL MPI_ALLREDUCE(pqtemp_it(1,1,1,1,1,1,1,1,1,1,1,1),pqtemp_i(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

              ELSE

                 CALL MPI_BARRIER(NEW_COMM, ierr)           
                 CALL MPI_ALLREDUCE(pqtemp_it(1,1,1,1,1,1,1,1,1,1,1,1),pqtemp_i(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

              END IF

              DEALLOCATE(pqtemp_it)

              DO iedu = 1, Neduc
                 DO ipau = 1, Npaudits
                    DO iwealth = 1, Nwealth
                       DO ipast = 1, Npast_t
                          DO itermi = 2, Nnterms
                             DO ipasti = 1, Npast
                                DO agei = 1, agen
                                   DO iedui = 1, Neduc
                                      DO iwealthi = 1, Nwealth
                                         DO elap = 1, Nelap                                         
                                            DO iq = 1, Nq
                                               DO isteal = 1, Nsteal
                                                  IF ((itermi == 1 .OR. ipasti == 1) .AND. isteal > 1) CYCLE
                                                  
                                                  IF (pqtemp_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) < 0.99d0 .OR. pqtemp_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) > 1.001d0) THEN
                                                     IF (myrank_t == 0) WRITE(*,*) 'wrong prob pqtemp_i', pqtemp_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq),itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq
                                                     
                                                  END IF
                                               END DO
                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
              DEALLOCATE(pqtemp_i)

           END IF

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)              
              CALL MPI_ALLREDUCE(vemax_voter_it(1,1,1,1,1,1,1,1,1,1,1,1),vemax_voter_i(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              
           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)           
              CALL MPI_ALLREDUCE(vemax_voter_it(1,1,1,1,1,1,1,1,1,1,1,1),vemax_voter_i(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              
           END IF           
           DEALLOCATE(vemax_voter_it)

           DO isteal = 1, Nsteal

                 ! If term = 1, those variables are all equal to the value when isteal=1 independently of ipast
                 vemax_voter_i(1,:,:,:,:,:,:,:,:,:,isteal,:) = vemax_voter_i(1,:,:,:,:,:,:,:,:,:,1,:) 

                 ! If iterm = 2, those variables are all equal to the value when isteal=1 if ipast = 1
                 vemax_voter_i(2:Nnterms,:,1,:,:,:,:,:,:,:,isteal,:) = vemax_voter_i(2:Nnterms,:,1,:,:,:,:,:,:,:,1,:) 

           END DO
           
           DO age = 1, agen
              vemax_voter_i_age(t,imun,:,age,:,:,:,:,:,:,:,:,:,:) = vemax_voter_i(:,age,:,:,:,:,:,:,:,:,:,:)
           END DO
           
           !3. Compute the value function of a voter if the election this period is won by the challenger           
           ! In vemax_voter_c we store the expected value function of voters with the expectation taken over different challengers
           ALLOCATE(vemax_voter_ct(Nelap,Npast_t,Nwealth,Npaudits,Neduc), vemax_voter_c(Nelap,Npast_t,Nwealth,Npaudits,Neduc))
           ALLOCATE(temp_prob_ct(Nelap,Npast_t,Nwealth,Npaudits,Neduc), temp_prob_c(Nelap,Npast_t,Nwealth,Npaudits,Neduc))           
           ! In vemax_voter_c_all we store the expected value function of voters for different challengers
           ALLOCATE(vemax_voter_ct_all(agen,Nwealth,Neduc,Nelap,Npast_t,Nwealth,Npaudits,Neduc), vemax_voter_c_all(agen,Nwealth,Neduc,Nelap,Npast_t,Nwealth,Npaudits,Neduc))
           ALLOCATE(temp_prob_ct_all(agen,Nwealth,Neduc,Nelap,Npast_t,Nwealth,Npaudits,Neduc), temp_prob_c_all(agen,Nwealth,Neduc,Nelap,Npast_t,Nwealth,Npaudits,Neduc))           
           vemax_voter_ct = 0d0
           vemax_voter_c = 0d0
           temp_prob_ct = 0d0
           temp_prob_c = 0d0
           vemax_voter_ct_all = 0d0
           vemax_voter_c_all = 0d0
           temp_prob_ct_all = 0d0
           temp_prob_c_all = 0d0
          
           counter3 = 0
           ! Variables that chacaracterie the past mayor
           DO iedu = 1, Neduc                      
              ! The probability of being audited may differ across terms
              DO ipau = 1, Npaudits
                 ! We don't need to change paudit_g if itermi = Nnterms beause here the new mayor is a challenger
                 paudit_g = paudit(0,ipau)
                 
                 !Net Wealth
                 DO iwealth = 1, Nwealth
                    wealthin = wealth(iwealth)
                    ! The last value for ipast are need to compute the value function of voters as they have different average wages
                    ! ipast = 1 for the past mayor, ipast = 2 for the voter
                    ! We only need ipast=1 for past mayors because wages do not depend on ipast
                    DO ipast = 1, Npast_t
                       IF (ipast < Npast_t) THEN
                          pmwage = wage_pastmayor(t,imun,iedu,ipast)
                       ELSE
                          pmwage = wage_vot(imun)
                       END IF
                       ! electoral appeal of the incumbent
                       DO elap = 1, Nelap

                          counter3 = counter3 + 1
                          IF ((counter3 <= ntasks3*nprocs_t .AND. counter3 >= myrank_t*ntasks3+1 .AND. counter3 <= myrank_t*ntasks3+ntasks3) .OR. &
                               (counter3 > ntasks3*nprocs_t .AND. counter3 - ntasks3*nprocs_t - 1 == myrank_t)) THEN

                             ! Characteristics of the challenger that affect the production of qcons                       
                             itermi = 1
                             ipasti = 1
                             isteal = 1
                             ! We don't need ifine
                             ifine = 1
                             iq = 1
                             DO iedui = 1, Neduc
                                DO iwealthi = 1, Nwealth
                                   DO agei = 1, agen
                                      agemayort = agemayor(agei)

                                      DO ia = 1, Nab
                                         DO ifu = 1, Nfunds
                                            DO ipr = 1, Npr
                                               
                                               qconsi = qconsout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)
                                               newsteal = stealout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)
                                               new_fr_stolen_g = newsteal/funds(ifu)
                                               newsavi = newsavout(agemayor(agei),imun,elap,itermi,ipr,ifu,iwealthi,ipau,ifine,ia,iedui)

                                               !We read in the expected utility of public consumption produced by the incumbent above
                                               ! This is used inside the utility function of the non-mayor individual E(qcons**(1-delta)/(1-delta))
                                               IF (ABS(delta-1d0) < small_no) THEN
                                                  ELNqcons = LOG(qconsi)
                                               ELSE
                                                  ELNqcons = (qconsi**(1d0-delta)/(1d0-delta))
                                               END IF
                                               ! This is used as an input in the value function E(log(qcons))
                                               ELNqcons_g = LOG(qconsi)
                                               
                                               inewwealthi=0
                                               IF(newsavi < (wealth(2)+wealth(1))/2d0) THEN
                                                  inewwealthi=1
                                                  GO TO 466
                                               END IF
                                               DO isav = 2, Nwealth-1
                                                  IF(newsavi >= (wealth(isav)+wealth(isav-1))/2d0 .AND. newsavi < (wealth(isav+1)+wealth(isav))/2d0) THEN
                                                     inewwealthi=isav
                                                     GO TO 466
                                                  END IF
                                               END DO
                                               IF(newsavi >=(wealth(Nwealth)+wealth(Nwealth-1))/2d0) THEN
                                                  inewwealthi = Nwealth
                                               END IF
466                                            IF(inewwealthi==0) WRITE(*,*) 'Wrong beta assignmentL2,inewwealthi',inewwealthi,newsavi
                                               
                                               ! As itermi = 1, itermi always < Nterms
                                               IF (t < Tend) THEN
                                                  IF (jj == 1 .AND. t >= 5) THEN  
                                                     IF (itermi < Nnterms .AND. agemayor(agei) < MIN(Tend-1,Retage-1)) THEN
                                                        ALLOCATE(betat1(MMsteal_q), betat2(MMsteal_q))
                                                        MMg = MMsteal_q
                                                        betat1(:) = betapmayortemp1(t+1,imun,itermi+1,agemayor(agei),1,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                        betat2(:) = betapmayortemp1(t+1,imun,itermi+1,agemayor(agei),2,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                        IF (flag_no_run == 1 .OR. flag_norun_prob_policy == 1) THEN
                                                           ALLOCATE(betat3(Nwealth))
                                                           betat3(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                        END IF
                                                     ELSE IF (itermi >= Nnterms .OR. agemayor(agei) >= MIN(Tend-1,Retage-1)) THEN
                                                        ALLOCATE(betat1(Nwealth), betat2(Nwealth))
                                                        MMg = Nwealth
                                                        betat1(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                        betat2(:) = betat1(:)
                                                     END IF
                                                  ELSE
                                                     IF (itermi < Nnterms .AND. agemayor(agei) < Retage-1) THEN
                                                        ALLOCATE(betat1(MMage_steal_q), betat2(MMage_steal_q))
                                                        MMg = MMage_steal_q
                                                        betat1(:) = betapmayor(t+1,imun,itermi+1,1,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                        betat2(:) = betapmayor(t+1,imun,itermi+1,2,iedui,ipast,inewwealthi,ipau,iedu,elap,:)
                                                        IF (flag_no_run == 1 .OR. flag_norun_prob_policy == 1) THEN
                                                           ALLOCATE(betat3(Nwealth))
                                                           betat3(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                        END IF
                                                     ELSE IF (itermi >= Nnterms .OR. agemayor(agei) >= Retage -1) THEN
                                                        ALLOCATE(betat1(Nwealth), betat2(Nwealth))
                                                        MMg = Nwealth
                                                        betat1(:) = betapmayornor(t+1,imun,ipast,ipau,iedu,elap,:)
                                                        betat2(:) = betat1(:)
                                                     END IF
                                                  END IF
                                               END IF
                                               
                                               ! The current mayor is a challenger, it must therefore be in term = 1; this is used in pastmayorsolution
                                               itermi_g = 1
                                               !Here we determine the optimal decisions of the incumbent if not reelected 
                                               !This subroutine produces as output the global variables: vemaxoptpmg, pconsoptpmg, qconsoptpmg, newsavoptpmg, utiloptpmg, emaxoptpmg, obtained in pastmayorsolution.f90 
                                               !He does not pay the cost of running, this is why we have the 0d0 at the end
                                               CALL notmayordecision(t,pmwage,wealthin,ELNqcons)               

                                               probqcons_ct = probage*probedu(iedui)*pwealth(iwealthi)*SUM(nonpardist_wealth_fu_pr(:,ifu,ipr)*pability(ia))
                                               probqcons_ct_all = SUM(nonpardist_wealth_fu_pr(:,ifu,ipr)*pability(ia))
                                                  
                                               IF (t >= Tend) THEN
                                                  
                                                  IF (utiloptpmg > -check_infty) THEN
                                                     vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) + utiloptpmg*probqcons_ct
                                                     vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) + utiloptpmg*probqcons_ct_all
                                                  ELSE
                                                     vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) + (min_util-per_min_util*ABS(min_util))*probqcons_ct
                                                     vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) + (min_util-per_min_util*ABS(min_util))*probqcons_ct_all
                                                  END IF
                                                  
                                               ELSE
                                                  vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct(elap,ipast,iwealth,ipau,iedu) + vemaxoptpmg*probqcons_ct
                                                  vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) = vemax_voter_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) + vemaxoptpmg*probqcons_ct_all
                                                  
                                                  DEALLOCATE(betat1, betat2)
                                                  IF (ALLOCATED(betat3)) DEALLOCATE(betat3)
                                                  
                                               END IF

                                               temp_prob_ct(elap,ipast,iwealth,ipau,iedu) = temp_prob_ct(elap,ipast,iwealth,ipau,iedu) + probqcons_ct
                                               temp_prob_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) = temp_prob_ct_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) + probqcons_ct_all
                                               
                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO
                             END DO
                             
                          END IF

                       END DO
                    END DO
                 END DO
              END DO
           END DO

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(vemax_voter_ct(1,1,1,1,1),vemax_voter_c(1,1,1,1,1),Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(temp_prob_ct(1,1,1,1,1),temp_prob_c(1,1,1,1,1),Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(vemax_voter_ct_all(1,1,1,1,1,1,1,1),vemax_voter_c_all(1,1,1,1,1,1,1,1),agen*Nwealth*Neduc*Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(temp_prob_ct_all(1,1,1,1,1,1,1,1),temp_prob_c_all(1,1,1,1,1,1,1,1),agen*Nwealth*Neduc*Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              
           ELSE
              
              CALL MPI_BARRIER(NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(vemax_voter_ct(1,1,1,1,1),vemax_voter_c(1,1,1,1,1),Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(temp_prob_ct(1,1,1,1,1),temp_prob_c(1,1,1,1,1),Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(vemax_voter_ct_all(1,1,1,1,1,1,1,1),vemax_voter_c_all(1,1,1,1,1,1,1,1),agen*Nwealth*Neduc*Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(temp_prob_ct_all(1,1,1,1,1,1,1,1),temp_prob_c_all(1,1,1,1,1,1,1,1),agen*Nwealth*Neduc*Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              
           END IF
           vemax_voter_c_age(t,imun,:,:,:,:,:) = vemax_voter_c(:,:,:,:,:)
           DO age = 1, agen
              vemax_voter_c_age_all(t,imun,age,:,:,:,:,:,:,:) = vemax_voter_c_all(age,:,:,:,:,:,:,:)
           END DO

           DO elap = 1, Nelap
              DO ipast = 1, Npast
                 DO iwealth = 1, Nwealth
                    DO ipau = 1, Npaudits
                       DO iedu = 1, Neduc

                          IF (temp_prob_c(elap,ipast,iwealth,ipau,iedu) < 0.99d0 .OR. temp_prob_c(elap,ipast,iwealth,ipau,iedu) > 1.001d0) THEN
                             IF (myrank_t == 0) WRITE(*,'(a,5i5,1f20.10)') 'wrong prob vemax_voer_c', elap,ipast,iwealth,ipau,iedu,temp_prob_c(elap,ipast,iwealth,ipau,iedu)
                          END IF

                          DO iedui = 1, Neduc
                             DO iwealthi = 1, Nwealth
                                DO agei = 1, agen
                                   
                                   IF (temp_prob_c_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) < 0.99d0 .OR. temp_prob_c_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu) > 1.001d0) THEN
                                      IF (myrank_t == 0) WRITE(*,'(a,8i5,1f20.10)') 'wrong prob vemax_voer_c', agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu,temp_prob_c_all(agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu)
                                   END IF
                                   
                                END DO
                             END DO
                          END DO
                          
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           DEALLOCATE(vemax_voter_ct, temp_prob_ct)
           DEALLOCATE(vemax_voter_ct_all, temp_prob_ct_all)

           ! We compute the approximation of vemax_voter_i and vemax_voter_c_all over ability, wealth, and age needed to determine in simulatemun.f90 whether an incumbent is elected
           IF (jj == 2 .AND. t == 5) THEN

              ! Approximation of vemax_voter_it
              
              ! The ipast of voters is == 1 because it only affects their wages and we don't find and effect of ipast in the wage
              ! The voters' iwealth takes also only one value by municipality size
              ! We can therefore ignore the voter's ipast and iwealth
              ALLOCATE(beta_voter_it(Nnterms,Npast,Neduc,Npaudits,Neduc,Nelap,Tend,MMage_steal_q),beta_voter_itt(Nnterms,Npast,Neduc,Npaudits,Neduc,Nelap,Tend,MMage_steal_q))
              beta_voter_it = 0d0
              beta_voter_itt = 0d0
              ALLOCATE(vemax_voter_i_temp(Nwealth,agen,Nsteal,Nq))
              vemax_voter_i_temp = 0d0

              loop_vf3 = Neduc*Npaudits*Neduc*Npast*(Nnterms-1)*Nelap
              ALLOCATE(temp_vfun(MMage_steal_q))
              temp_vfun = 0d0
              
              ntasks_vf3 = INT(loop_vf3/nprocs_t)
              restasks_vf3 = loop_vf3 - ntasks_vf3*nprocs_t
              
              ! For voters, iwealth_vec contains the indices for the average wealth by municipality size
              iwealth = iwealth_vec(imun)
              ! For voters, the correct value function is the ones that corresponds to ipast = 2, which uses the average wage for low-educated for the corresponding municipality size
              ipast = Npast_t
              counter_vf3 = 0
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iedui = 1, Neduc
                       DO ipasti = 1, Npast
                          DO itermi = 2, Nnterms
                             DO elap = 1, Nelap

                                count_steal = 0
                                count_q = 0
                                vemax_voter_i_temp = 0d0
                                ! The approximation is over the wealth of the past mayor and not of the incumbent
                                DO agei = 1, ageN
                                   DO iwealthi = 1, Nwealth
                                      DO iq = 1, Nq
                                         DO isteal = 1, Nsteal
                                            
                                            vemax_voter_i_temp(iwealthi,agei,isteal,iq) = vemax_voter_i_age(t,imun,itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)
                                            IF (isteal > 1) THEN
                                               IF (ABS(vemax_voter_i_temp(iwealthi,agei,isteal,iq)-vemax_voter_i_temp(iwealthi,agei,isteal-1,iq)) > thres_count) count_steal = count_steal + 1
                                            END IF
                                            IF (iq > 1) THEN
                                               IF (ABS(vemax_voter_i_temp(iwealthi,agei,isteal,iq)-vemax_voter_i_temp(iwealthi,agei,isteal,iq-1)) > thres_count) count_q = count_q + 1
                                            END IF
                                            
                                         END DO
                                      END DO
                                   END DO
                                END DO

                                counter_vf3 = counter_vf3 + 1
                                IF ((counter_vf3 <= ntasks_vf3*nprocs_t .AND. counter_vf3 >= myrank_t*ntasks_vf3+1 .AND. &
                                     counter_vf3 <= myrank_t*ntasks_vf3+ntasks_vf3) .OR. &
                                     (counter_vf3 > ntasks_vf3*nprocs_t .AND. counter_vf3 - ntasks_vf3*nprocs_t-1 == myrank_t)) THEN
                                   
                                   
                                   IF (count_q < 21 .AND. count_steal < 21) THEN
                                      CALL vfunapprox_age(agen,agemayor(:),vemax_voter_i_temp(:,:,1,1),temp_vfun(:))
                                   ELSE IF (count_q >= 21 .AND. count_steal < 21) THEN
                                      CALL vfunapprox_age_q(agen,agemayor(:),vemax_voter_i_temp(:,:,1,:),temp_vfun(:))
                                   ELSE IF (count_q < 21 .AND. count_steal >= 21) THEN
                                      CALL vfunapprox_age_steal(agen,agemayor(:),vemax_voter_i_temp(:,:,:,1),temp_vfun(:))
                                   ELSE
                                      CALL vfunapprox_age_steal_q(agen,agemayor(:),vemax_voter_i_temp(:,:,:,:),temp_vfun(:))
                                   END IF
                                   beta_voter_it(itermi,ipasti,iedui,ipau,iedu,elap,t,:) = temp_vfun(:)
                                   
!!$                                write(*,'(a,8i5,18f14.8)') 'beta_voter_i', count_steal, count_q, itermi,ipasti,iedui,ipau,iedu,t, beta_voter_it(itermi,ipasti,iedui,ipau,iedu,t,:)
                                   
                                END IF

                             END DO
                          END DO
                       END DO
                    
!!$                          if (myrank_t == 0) write(*,'(a,9i5,2f20.10)') 'vemax_voter_i', agei,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu, vemax_voter_i(2,agei,2,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu), vemax_voter_i(2,agei,3,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu)
                       
                    END DO
                 END DO
              END DO

              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
                 
                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
                 CALL MPI_ALLREDUCE(beta_voter_it(1,1,1,1,1,1,1,1), beta_voter_itt(1,1,1,1,1,1,1,1), Nnterms*Npast*Neduc*Npaudits*Neduc*Nelap*Tend*MMage_steal_q,MPI_REAL8,MPI_SUM, MPI_COMM_WORLD, ierr)

              ELSE
                 
                 CALL MPI_BARRIER(NEW_COMM, ierr)
                 CALL MPI_ALLREDUCE(beta_voter_it(1,1,1,1,1,1,1,1), beta_voter_itt(1,1,1,1,1,1,1,1), Nnterms*Npast*Neduc*Npaudits*Neduc*Nelap*Tend*MMage_steal_q,MPI_REAL8,MPI_SUM, NEW_COMM, ierr)

              END IF
                 
              DEALLOCATE(beta_voter_it)
              
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iedui = 1, Neduc
                       DO ipasti = 1, Npast
                          DO itermi = 2, Nnterms
                             DO elap = 1, Nelap

                                beta_voter_i(t,imun,itermi,ipasti,iedui,ipau,iedu,elap,:) = beta_voter_itt(itermi,ipasti,iedui,ipau,iedu,elap,t,:)
                                   
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
              
              DEALLOCATE(beta_voter_itt, vemax_voter_i_temp, temp_vfun)

              ! Approximation of vemax_voter_c_all, needed to compute the prob of winning the election against a particular challenger in simulatemun
              ALLOCATE(beta_voter_ct(Neduc,Npaudits,Neduc,Nelap,Tend,MMage),beta_voter_ctt(Neduc,Npaudits,Neduc,Nelap,Tend,MMage))
              beta_voter_ct = 0d0
              beta_voter_ctt = 0d0
              ALLOCATE(vemax_voter_c_temp(Nwealth,agen))
              vemax_voter_c_temp = 0d0

              loop_vf3 = Neduc*Npaudits*Neduc*Nelap
              ! temp_vfun has dimention MMage_steal_q and not MMage because vfunapprox_age has an output array of dimension MMage_steal_q required by beta_vote_i
              ALLOCATE(temp_vfun(MMage_steal_q))
              temp_vfun = 0d0
              
              ntasks_vf3 = INT(loop_vf3/nprocs_t)
              restasks_vf3 = loop_vf3 - ntasks_vf3*nprocs_t
              
              ! For voters, iwealth_vec contains the indices for the average wealth by municipality size
              iwealth = iwealth_vec(imun)
              ! For voters, the correct value function is the ones that corresponds to ipast = 2, which uses the average wage for low-educated for the corresponding municipality size
              ipast = Npast_t
              counter_vf3 = 0
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iedui = 1, Neduc
                       DO elap = 1, Nelap

                          vemax_voter_c_temp = 0d0
                          ! The approximation is over the wealth of the past mayor and not of the incumbent
                          DO agei = 1, ageN
                             DO iwealthi = 1, Nwealth
                                
                                vemax_voter_c_temp(iwealthi,agei) = vemax_voter_c_age_all(t,imun,agei,iwealthi,iedui,elap,ipast,iwealth,ipau,iedu)
                                
                             END DO
                          END DO
                          
                          counter_vf3 = counter_vf3 + 1
                          IF ((counter_vf3 <= ntasks_vf3*nprocs_t .AND. counter_vf3 >= myrank_t*ntasks_vf3+1 .AND. &
                               counter_vf3 <= myrank_t*ntasks_vf3+ntasks_vf3) .OR. &
                               (counter_vf3 > ntasks_vf3*nprocs_t .AND. counter_vf3 - ntasks_vf3*nprocs_t-1 == myrank_t)) THEN
                             
                             CALL vfunapprox_age(agen,agemayor(:),vemax_voter_c_temp(:,:),temp_vfun(:))
                             ! The regression parameters are contained in positions 1:Nwealth+1+Npol_age; the remaining spots are 0 and only need for beta_vote_i
                             beta_voter_ct(iedui,ipau,iedu,elap,t,:) = temp_vfun(1:MMage)
                             
!!$                                write(*,'(a,8i5,18f14.8)') 'beta_voter_i', count_steal, count_q, itermi,ipasti,iedui,ipau,iedu,t, beta_voter_it(itermi,ipasti,iedui,ipau,iedu,t,:)
                             
                          END IF
                          
                       END DO
                    END DO
                 END DO
                 
!!$                          if (myrank_t == 0) write(*,'(a,9i5,2f20.10)') 'vemax_voter_i', agei,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu, vemax_voter_i(2,agei,2,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu), vemax_voter_i(2,agei,3,elapi,iedui,iwealthi,iai,ipast,iwealth,ipau,iedu)
                       
              END DO
              
              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
                 
                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
                 CALL MPI_ALLREDUCE(beta_voter_ct(1,1,1,1,1,1), beta_voter_ctt(1,1,1,1,1,1), Neduc*Npaudits*Neduc*Nelap*Tend*MMage,MPI_REAL8,MPI_SUM, MPI_COMM_WORLD, ierr)

              ELSE
                 
                 CALL MPI_BARRIER(NEW_COMM, ierr)
                 CALL MPI_ALLREDUCE(beta_voter_ct(1,1,1,1,1,1), beta_voter_ctt(1,1,1,1,1,1), Neduc*Npaudits*Neduc*Nelap*Tend*MMage,MPI_REAL8,MPI_SUM, NEW_COMM, ierr)

              END IF
                 
              DEALLOCATE(beta_voter_ct)
              
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iedui = 1, Neduc
                       DO elap = 1, Nelap
                          
                          beta_voter_c(t,imun,iedui,ipau,iedu,elap,:) = beta_voter_ctt(iedui,ipau,iedu,elap,t,:)
                                   
                       END DO
                    END DO
                 END DO
              END DO
              
              DEALLOCATE(beta_voter_ctt, vemax_voter_c_temp, temp_vfun)
              
           END IF
           
           ALLOCATE(Pr_i_wintt(Tend,Npast,Neduc,Nwealth,Npaudits,Nnterms,Nsteal,Nq,Nelap,Tend,Neduc,Nwealth),Pr_i_wint(Tend,Npast,Neduc,Nwealth,Npaudits,Nnterms,Nsteal,Nq,Nelap,Tend,Neduc,Nwealth))
           Pr_i_wintt = 0d0
           Pr_i_wint = 0d0

           ! NOW WE FIND THE PROBABILITY THAT AN INCUMBENT WINS THE ELECTION CONDITIONAL ON RUNNING FOR EACH VOTER'S TYPE
           counter4 = 0
           ! We consider each possible state variable for the voter
           ! As we don't have wealth data for the general population, we only have municipality size and education as state variables
           ! For voters, iwealth_vec contains the indices for the average wealth by municipality size
           iwealth = iwealth_vec(imun)
           ! For voters, the correct value function is the ones that corresponds to ipast = 2, which uses the average wage for low-educated for the corresponding municipality size
           ipast = Npast_t
           iedu = 1
           ! And each each possible state variable for the incumbent
           !The probability of being audited has to do with the incumbent and not with voters
           ! We normalize popsize to 1
           popsizet = 1d0
           ! age of the voter that we use to compute P_win
           IF (jj == 1 .AND. t > 5) THEN
              voter_age = t
           ELSE
              ! We use the voter of age 5
              voter_age = 5
           END IF
!!$           popsize_typet(:) = popsize_type(:,imun)/age_size
           DO ipau = 1, Npaudits
              DO iwealthi = 1, Nwealth
                 DO iedui = 1, Neduc
                    av_qcons_vec(t,imun,ipau) = SUM(qconsout(t,imun,:,1,:,:,:,ipau,:,:,:))/DBLE(Nelap*Npr*Nfunds*Nfines*Nab*Nwealth*Neduc)
                    av_qcons = av_qcons_vec(t,imun,ipau)
                    
                    DO ipasti = 1, Npast
                       past_g = 0d0
                       IF (ipasti == 2) past_g = 1d0
                       DO agei = 1, agen
                          
                          counter4 = counter4 + 1
                          IF ((counter4 <= ntasks4*nprocs_t .AND. counter4 >= myrank_t*ntasks4+1 .AND. counter4 <= myrank_t*ntasks4+ntasks4) .OR. &
                               (counter4 > ntasks4*nprocs_t .AND. counter4 - ntasks4*nprocs_t - 1 == myrank_t)) THEN
                             
                             ! The incumbent must be in term > 1
                             DO itermi = 2, Nnterms
                                DO iq = 1, Nq
                                   qconsil = qconsvec_t(iq)
!!$                                   diff_qcons = qconsvec_t(iq) - LOG(av_qcons)
!!$                                   diff_qcons = qconsvec_t(iq)
!!$                                   ! qconsvec(imun,2) is average per capita public consumption in municipality imun in the data
                                   diff_qcons = qconsvec_t(iq) - LOG(qconsvec(imun,2))

                                   ! Incumbent's electoral appeal
                                   DO elap = 1, Nelap

                                      ! Incumbent's past stealing and fine
                                      DO isteal = 1, Nsteal
                                         IF (ipasti == 1 .AND. isteal > 1) CYCLE
                                         fr_stolenit = fr_stoleni(isteal)

                                         ! Challenger's observables
                                         DO iwealthc = 1, Nwealth
                                            DO ieduc = 1, Neduc
                                               DO agec = 1, agen
                                         
                                                  alpha_nstt = 0d0
                                                  IF (ipasti == 2 .AND. fr_stolenit <= 0d0) alpha_nstt = alpha_nst
                                                  
                                                  alpha_eat = 0d0
                                                  IF (ipasti == 2 .AND. fr_stolenit > 0d0) alpha_eat = - alpha_ea
                                                  
                                                  ! We use the youngest voter older than 5 that we have
                                                  vemax_voter_i_pp = vemax_voter_i_age(voter_age,imun,itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)
!!$                                               vemax_voter_c_pp = vemax_voter_c_age(voter_age,imun,elap,ipast,iwealth,ipau,iedu)
                                                  vemax_voter_c_pp = vemax_voter_c_age_all(voter_age,imun,agec,iwealthc,ieduc,elap,ipast,iwealth,ipau,iedu)  
                                                  
                                                  arg_exp = -(vemax_voter_i_pp - vemax_voter_c_pp + alpha_ie + alpha_nstt + alpha_eat + alpha_st*past_g*fr_stolenit + alpha_q*diff_qcons)
                                                  
                                                  IF (arg_exp > -50d0 .AND.arg_exp < 50d0) THEN
                                                     pp = 1d0/(1d0 + EXP(arg_exp))
                                                  ELSE IF (arg_exp <= -50d0) THEN
                                                     pp = 1d0-small_no
                                                  ELSE IF (arg_exp >= 50d0) THEN
                                                     pp = small_no
                                                  END IF
                                                  
!!$                                write(*,'(a,1i4,7f14.7)') 'pp', itheta,  pp(itheta), vemax_voter_i_pp, vemax_voter_c_pp, alpha_ie, alpha_nstt, alpha_eat, vemax_voter_i_pp - vemax_voter_c_pp + alpha_ie
                                      
                                         ! Argument inside the normal distribution after standardization for at least N/2 votes
!!$                                         IF (pp > small_no .AND. pp < 1d0-small_no) THEN
!!$                                            Phi_arg = popsizet**0.5d0*(0.5d0-pp)/(pp*(1d0-pp))**0.5d0
!!$                                         ELSE IF (pp <= small_no) THEN
!!$                                            Phi_arg = -50d0
!!$                                         ELSE IF (pp >= 1d0-small_no) THEN
!!$                                            Phi_arg = 50d0
!!$                                         END IF
                                                  Phi_arg = popsizet**0.5d0*(0.5d0-pp)/(pp*(1d0-pp))**0.5d0
                                                  Pr_i_wintt(agemayor(agei),ipasti,iedui,iwealthi,ipau,itermi-1,isteal,iq,elap,agemayor(agec),ieduc,iwealthc) = 1d0 - pnorm(Phi_arg)

                                                  ! If we consider a policy in which a politician cannot run is caught stealing
                                                  IF (flag_no_run == 1 .AND. ipasti == 2 .AND. isteal > 1) THEN
                                                     Pr_i_wintt(agemayor(agei),ipasti,iedui,iwealthi,ipau,itermi-1,isteal,iq,elap,agemayor(agec),ieduc,iwealthc) = 0d0
                                                  END IF
                                         
                                                  ! If we consider a policy in which a politician cannot run is caught stealing and convicted; we use a conviction prob = prob_conv_norun
                                                  IF (flag_norun_prob_policy == 1 .AND. ipasti == 2 .AND. fr_stoleni(isteal) > l_fr_stolen_x) THEN
                                                     Pr_i_wintt(agemayor(agei),ipasti,iedui,iwealthi,ipau,itermi-1,isteal,iq,elap,agemayor(agec),ieduc,iwealthc) = Pr_i_wintt(agemayor(agei),ipasti,iedui,iwealthi,ipau,itermi-1,isteal,iq,elap,agemayor(agec),ieduc,iwealthc)*(1d0 - prob_conv_norun)
                                                  END IF

                                               END DO
                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO
                             END DO
                             
                          END IF
                          
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN

              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(Pr_i_wintt(1,1,1,1,1,1,1,1,1,1,1,1),Pr_i_wint(1,1,1,1,1,1,1,1,1,1,1,1),Tend*Npast*Neduc*Nwealth*Npaudits*Nnterms*Nsteal*Nq*Nelap*Tend*Neduc*Nwealth, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(Pr_i_wintt(1,1,1,1,1,1,1,1,1,1,1,1),Pr_i_wint(1,1,1,1,1,1,1,1,1,1,1,1),Tend*Npast*Neduc*Nwealth*Npaudits*Nnterms*Nsteal*Nq*Nelap*Tend*Neduc*Nwealth, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

           END IF
           DEALLOCATE(Pr_i_wintt)

           DO isteal = 1, Nsteal

                 ! If past = 1, those variables are all equal to the value when isteal=1 (these are all incumbents)
                 Pr_i_wint(:,1,:,:,:,:,isteal,:,:,:,:,:) = Pr_i_wint(:,1,:,:,:,:,1,:,:,:,:,:) 

           END DO

           Pr_i_win(imun,:,:,:,:,:,:,:,:,:,:,:,:) = Pr_i_wint(:,:,:,:,:,:,:,:,:,:,:,:)

           DEALLOCATE(Pr_i_wint)
           
           ! WE CAN NOW COMPUTE THE EXPECTED VALUE FOR:
           ! 1. INCUMBENTS WHO WON THE ELECTIONS
           ! 2. INCUMBENTS WHO LOST THE ELECTIONS
           ! 3. PAST MAYORS WITH INCUMBENT MAYORS
           ! 4. PAST MAYORS WITH CHALLENGER MAYORS

           !We compute the probabilities because it varies with municipal size
           CALL probemax(imun,t,agemayor(:),agen)  

           IF (jj == 2) THEN
              IF (t > Retage) THEN 
                 GO TO 8834
              ELSE IF (t == Retage) THEN
                 GO TO 8234
              END IF
           END IF
           
           !WE COMPUTE THE EXPECTED VALUE OF AN INCUMBET WHO CHOSE TO RUN
           
           !1. We first compute the part that considers the incumbent being reelected
           counter5 = 0
           !education of the individual
           DO iedu = 1, Neduc
              !This variable describes the type of mayor:
              DO ia = 1, Nab
                 !The fraction of the maximum fine paid by the corrupt mayor is a random variable discretized using Nfines points
                 !We can use the Kumaraswamy distribution
                 ifine = 1
                 !The probability of being audit may differ across terms
                 DO ipau = 1, Npaudits
                    
                    !CURRENT VARIABLES
                    !savings
                    DO iwealth = 1, Nwealth
                       !funds received by the municipality (not the incumbent) from central goverment
                       DO ifu = 1, Nfunds
                          !private inputs in the production function for public consumption
                          DO ipr = 1, Npr
                             !We start from iterm = 2 because iterm = 1 only for a challanger who was elected
                             DO iterm = 2, Nnterms
                                !This variable describes the past of the mayor; 1 = no audit; 2= audit & no steal; 3 = audit & steal>0; Only relevant for 2nd term mayors!
                                DO ipast = 1, Npast
                                   
                                   counter5 = counter5 + 1
                                   IF ((counter5 <= ntasks5*nprocs_t .AND. counter5 >= myrank_t*ntasks5+1 .AND. counter5 <= myrank_t*ntasks5+ntasks5) .OR. &
                                        (counter5 > ntasks5*nprocs_t .AND. counter5 - ntasks5*nprocs_t - 1 == myrank_t)) THEN
                                      
                                      ! elap is the type of the incumbent
                                      DO elap = 1, Nelap
                                         DO iq = 1, Nq
                                            DO isteal = 1, Nsteal
                                               IF (ipast == 1 .AND. isteal > 1) GOTO 264
                                               
                                               ! We use iterm-1 for the probability because for incumbents we need to consider the prob of winning reelection before starting the next term
                                               IF (t >= Tend) THEN
                                                  
                                                  IF (utilt(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu) > -check_infty) THEN
                                                     
                                                     emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + &
                                                          utilt(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu)*SUM(probemax1(iedu,iterm-1,ifine,ipr,ifu,ipast,ipau,iwealth,isteal,iq,elap,:,:,:))
                                                     
                                                  ELSE
                                                     
                                                     emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + &
                                                          (min_util-per_min_util*ABS(min_util))*SUM(probemax1(iedu,iterm-1,ifine,ipr,ifu,ipast,ipau,iwealth,isteal,iq,elap,:,:,:))
                                                     
                                                  END IF
                                                  
                                               ELSE
                                                  
                                                  emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + &
                                                       vemaxt(elap,iterm,ipr,ifu,iwealth,ipau,ifine,ia,iedu)*SUM(probemax1(iedu,iterm-1,ifine,ipr,ifu,ipast,ipau,iwealth,isteal,iq,elap,:,:,:))
                                                  
                                               END IF
                                               
                                               ptempt_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = ptempt_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + SUM(probemax1(iedu,iterm-1,ifine,ipr,ifu,ipast,ipau,iwealth,isteal,iq,elap,:,:,:))
                                               
264                                         END DO
                                         END DO
                                      END DO
                                      
                                   END IF
                                      
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           DEALLOCATE(utilt)
           
!!$        WRITE(*,'(a,1i4,1f20.10)') 'ptempt_run i', myrank_t, ptempt_run(1,1,2,1,1,1,1)
           
           !1. We then consider the part that considers the incumbent losing the election
8234       counter6 = 0     

           ALLOCATE(emax_not(Nelap,Npast,Nwealth,Npaudits,Neduc))
           emax_not = 0d0

           ! Here we start the loop of education for the second loop!
           DO iedu = 1, Neduc
              
              ! Variables that chacaracterie the past mayor and determine his expected value function in this period
              ! The probability of being audited may differ across terms
              DO ipau = 1, Npaudits
                 !Net Wealth
                 DO iwealth = 1, Nwealth
                    ! This is the elap of the incumbent who lost the election
                    DO elap = 1, Nelap

                       ! Challenger's observable characteristics
                       DO iwealthc = 1, Nwealth
                          DO ieduc = 1, Neduc
                             DO agec = 1, agen
                                
                                ! We don't need the characteristics of the challenger because we only need the expected log of qcons                    
                                counter6 = counter6 + 1
                                IF ((counter6 <= ntasks6*nprocs_t .AND. counter6 >= myrank_t*ntasks6+1 .AND. counter6 <= myrank_t*ntasks6+ntasks6) .OR. &
                                     (counter6 > ntasks6*nprocs_t .AND. counter6 - ntasks6*nprocs_t - 1 == myrank_t)) THEN
                                   
                                   ! We first consider the case in which the incumbent chooses to run
                                   ! We need to consider the following incumbent's characteristics even if s/he lost the election because they affect the probability of reelection
                                   DO ia = 1, Nab
                                      DO iterm = 2, Nnterms
                                         ! The age of the mayor losing the election corresponds to t (agei)
                                         ! For a past mayorS only ipast = 1 is relevant, we therefore consider vemax_voter_c only for ipast = 1; but probemax2 depends on ipast = 1,2,3
                                         DO ipast = 1, Npast
                                            DO iq = 1, Nq
                                               DO isteal = 1, Nsteal
                                                  IF (ipast == 1 .AND. isteal > 1) GOTO 964
                                                  
                                                  emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_runt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + vemax_voter_c_all(agec,iwealthc,ieduc,elap,1,iwealth,ipau,iedu)*probemax2(iedu,iterm-1,ipast,ipau,iwealth,isteal,iq,elap,agec,ieduc,iwealthc)
                                                  ptempt_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = ptempt_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) + probemax2(iedu,iterm-1,ipast,ipau,iwealth,isteal,iq,elap,agec,ieduc,iwealthc)

                                                  
964                                            END DO
                                            END DO
                                         END DO
                                      END DO
                                   END DO

                                END IF
                                   
                             END DO
                          END DO
                       END DO
                                                             
!!$                       ! We then consider the case of a mayor who chooses not to run, then the variables that affect the electoral probabilities are no longer relevant
!!$                       ! only ipast = 1 is relevant given that he choses not to run
!!$                       emax_not(elap,:,iwealth,ipau,iedu) = emax_not(elap,:,iwealth,ipau,iedu) + vemax_voter_c(elap,1,iwealth,ipau,iedu)  
                       
                    END DO
                 END DO
              END DO
           END DO

           ! We then consider the case of a mayor who chooses not to run, then the variables that affect the electoral probabilities are no longer relevant
           ! only ipast = 1 is relevant given that he choses not to run
           DO ipast = 1, Npast
              emax_not(:,ipast,:,:,:) = vemax_voter_c(:,1,:,:,:)
           END DO
           
           ALLOCATE(emax_run(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq))
           emax_run = 0d0

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(emax_runt(1,1,1,1,1,1,1,1,1), emax_run(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
           ELSE
              CALL MPI_BARRIER(NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(emax_runt(1,1,1,1,1,1,1,1,1), emax_run(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
           END IF
           
           DEALLOCATE(emax_runt)

           DO isteal = 1, Nsteal

              ! If past = 1, those variables are all equal to the value when isteal=1
              emax_run(:,1,:,:,:,:,:,isteal,:) = emax_run(:,1,:,:,:,:,:,1,:) 
              ptempt_run(:,1,:,:,:,:,:,isteal,:) = ptempt_run(:,1,:,:,:,:,:,1,:)
                            
           END DO

           
           ALLOCATE(ptemp_run(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq))
           ptemp_run = 0d0

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              CALL MPI_ALLREDUCE(ptempt_run(1,1,1,1,1,1,1,1,1), ptemp_run(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)           
           ELSE
              CALL MPI_ALLREDUCE(ptempt_run(1,1,1,1,1,1,1,1,1), ptemp_run(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
           END IF
           DEALLOCATE(ptempt_run)
           
           IF (jj == 2 .AND. t < Retage) THEN
              
              !CALCULATING THE BETAS FOR DECISION OF RUNNING OR NOT RUNNING, CONDITIONAL ON THE AUDIT OUTCOME!        
              ALLOCATE(emax_run_temp(Nab,Nwealth,Nsteal,Nq),betasimrunt(Npast,Nnterms,Npaudits,Neduc,Nelap,MMability_steal_q), betasimruntt(Npast,Nnterms,Npaudits,Neduc,Nelap,MMability_steal_q), temp_vfun(MMability_steal_q))
              emax_run_temp =0d0; betasimrunt =0d0; temp_vfun = 0d0
              
              ! Compute the value function of an individual that enters t as mayor MAX(emax,emaxnor)
              ! We use the same subroutine (vfunapprox_Tend) for all periods (Tend and earlier periods
              ! Aproximating the max  value function
              loop_vf1 = Neduc*Npaudits*(Nnterms-1)*Npast*Nelap
              ntasks_vf1 = INT(loop_vf1/nprocs_t)
              restasks_vf1 = loop_vf1 - ntasks_vf1*nprocs_t
              
              counter_vf1 = 0d0
              DO iedu = 1, Neduc
                 DO ipau = 1, Npaudits
                    DO iterm = 2, Nnterms
                       DO ipast = 1, Npast
                          DO elap = 1, Nelap
                             
                             count_steal = 0
                             count_q = 0
                             emax_run_temp = 0d0
                             DO iwealth = 1, Nwealth
                                DO ia = 1, Nab
                                   DO iq = 1, Nq
                                      DO isteal = 1, Nsteal
                                         
                                         emax_run_temp(ia,iwealth,isteal,iq) = emax_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq)
                                         IF (isteal > 1) THEN
                                            IF (ABS(emax_run_temp(ia,iwealth,isteal,iq)-emax_run_temp(ia,iwealth,isteal-1,iq)) > thres_count) count_steal = count_steal + 1
                                         END IF
                                         IF (iq > 1) THEN
                                            IF (ABS(emax_run_temp(ia,iwealth,isteal,iq)-emax_run_temp(ia,iwealth,isteal,iq-1)) > thres_count) count_q = count_q + 1
                                         END IF
                                         
                                      END DO
                                   END DO
                                END DO
                             END DO

                             counter_vf1 = counter_vf1 + 1
                             IF ((counter_vf1 <= ntasks_vf1*nprocs_t .AND. counter_vf1 >= myrank_t*ntasks_vf1+1 .AND. &
                                  counter_vf1 <= myrank_t*ntasks_vf1+ntasks_vf1) .OR. &
                                  (counter_vf1 > ntasks_vf1*nprocs_t .AND. counter_vf1 - ntasks_vf1*nprocs_t-1 == myrank_t)) THEN
                                
                                IF (count_q < 21 .AND. count_steal < 21) THEN
                                   CALL vfunapprox_ability(emax_run_temp(:,:,1,1),temp_vfun(:))
                                ELSE IF (count_q >= 21 .AND. count_steal < 21) THEN
                                   CALL vfunapprox_ability_q(emax_run_temp(:,:,1,:),temp_vfun(:))
                                ELSE IF (count_q < 21 .AND. count_steal >= 21) THEN
                                   CALL vfunapprox_ability_steal(emax_run_temp(:,:,:,1),temp_vfun(:))
                                ELSE
                                   CALL vfunapprox_ability_steal_q(emax_run_temp(:,:,:,:),temp_vfun(:))
                                END IF
                                betasimrunt(ipast,iterm,ipau,iedu,elap,:) = temp_vfun(:)
                                
                             END IF

                          END DO
                       END DO
                    END DO
                 END DO
              END DO
              
              DEALLOCATE(emax_run_temp,temp_vfun)

              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
                 CALL MPI_ALLREDUCE(betasimrunt(1,1,1,1,1,1), betasimruntt(1,1,1,1,1,1), Npast*Nnterms*Npaudits*Neduc*Nelap*MMability_steal_q, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              ELSE
                 CALL MPI_BARRIER(NEW_COMM, ierr)
                 CALL MPI_ALLREDUCE(betasimrunt(1,1,1,1,1,1), betasimruntt(1,1,1,1,1,1), Npast*Nnterms*Npaudits*Neduc*Nelap*MMability_steal_q, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              END IF
              DEALLOCATE(betasimrunt)
              
              DO iedu = 1, Neduc
                 DO ipau = 1, Npaudits
                    DO iterm = 2, Nnterms
                       DO ipast = 1, Npast
                          DO ifup = 1, Nfunds
                             DO iprp = 1, Npr
                                DO elap = 1, Nelap

                                   betasimrun(t,imun,ipast,iterm,ipau,iedu,elap,:) = betasimruntt(ipast,iterm,ipau,iedu,elap,:)

                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
              
              DEALLOCATE(betasimruntt)
                            
           END IF

           ! We need to add the cost of running
           emax_run(:,:,:,:,:,:,:,:,:) = emax_run(:,:,:,:,:,:,:,:,:) - cost_run_frac ! - cost_run_frac_t !ABS(emax_run(:,:,:,:,:,:,:))*cost_run_frac

           ALLOCATE(emax_estt(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq), emax_est(Nelap,Npast,Nnterms,Nwealth,Npaudits,Nab,Neduc,Nsteal,Nq))
           emax_estt = 0d0; emax_est = 0d0
           ALLOCATE(pr_runtt(Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq), pr_runt(Npast,Nnterms,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           pr_runtt = 0d0; pr_runt = 0d0

           counter7 = 0
           ! This loop is for incumbents who chose to run
           DO iedu = 1, Neduc
              DO ia = 1, Nab
                 DO ipau = 1, Npaudits
                    DO iwealth = 1, Nwealth
                       ! They can only be terms 2 or higher, for iterm = 1 the probabilities are not well defined
                       DO iterm = 2, Nnterms
                          DO ipast = 1, Npast
                             DO elap = 1, Nelap

                                ! We don't need the characteristics of the challenger because we only need the expected log of qcons                    
                                counter7 = counter7 + 1
                                IF ((counter7 <= ntasks7*nprocs_t .AND. counter7 >= myrank_t*ntasks7+1 .AND. counter7 <= myrank_t*ntasks7+ntasks7) .OR. &
                                     (counter7 > ntasks7*nprocs_t .AND. counter7 - ntasks7*nprocs_t - 1 == myrank_t)) THEN

                                   DO iq = 1, Nq
                                      DO isteal = 1, Nsteal

                                         IF (emax_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) >= emax_not(elap,ipast,iwealth,ipau,iedu)) THEN
                                            emax_estt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq)
                                            pr_runtt(ipast,iterm,iwealth,ipau,iedu,isteal,iq) = pr_runtt(ipast,iterm,iwealth,ipau,iedu,isteal,iq) + pappeal(elap)*pability(ia)
                                         ELSE
                                            emax_estt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_not(elap,ipast,iwealth,ipau,iedu)
                                         END IF
!!$                                         IF (flag_no_run == 1 .AND. ipast == 2 .AND. isteal > 1) THEN
!!$                                            emax_estt(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) = emax_not(elap,ipast,iwealth,ipau,iedu)
!!$                                            pr_runtt(ipast,iterm,iwealth,ipau,iedu,isteal,iq) = 0d0
!!$                                         END IF

!!$                                         if (t>=4 .and. elap==1 .and. (iterm==1 .or. iterm==2) .and. isteal==1 .and. iq==1 .and. iwealth==5 .and. ipau==1 .and. ipast==1 .and. iedu==1) WRITE(*,'(a,9i5,5f20.10)') 'prun', elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq,emax_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq), emax_not(elap,ipast,iwealth,ipau,iedu), pappeal(elap), pability(ia), pr_runtt(ipast,iterm,iwealth,ipau,iedu,isteal,iq)

                                         !Check the probabilities add up to 1 when running
                                         IF (ptemp_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) < 0.99d0 .OR. ptemp_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq) > 1.001d0) THEN
                                            IF (myrank_t == 0) WRITE(*,*) 'wrong prob mayor 1', ptemp_run(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq),elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq
                                         END IF

                                      END DO
                                   END DO
                                   
                                END IF
                                
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           
           DEALLOCATE(ptemp_run)

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)              
              CALL MPI_ALLREDUCE(emax_estt(1,1,1,1,1,1,1,1,1), emax_est(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(pr_runtt(1,1,1,1,1,1,1), pr_runt(1,1,1,1,1,1,1), Npast*Nnterms*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)           
              CALL MPI_ALLREDUCE(emax_estt(1,1,1,1,1,1,1,1,1), emax_est(1,1,1,1,1,1,1,1,1), Nelap*Npast*Nnterms*Nwealth*Npaudits*Nab*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(pr_runtt(1,1,1,1,1,1,1), pr_runt(1,1,1,1,1,1,1), Npast*Nnterms*Nwealth*Npaudits*Neduc*Nsteal*Nq, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

           END IF

              
           DEALLOCATE(emax_estt, pr_runtt)

           pr_run(t,imun,:,:,:,:,:,:,:) = pr_runt(:,:,:,:,:,:,:)

           DEALLOCATE(pr_runt)

           DO iedu = 1, Neduc
              DO ipau = 1, Npaudits
                 DO ipast = 1, Npast
                    DO elap = 1, Nelap

                       IF (t == Tend) THEN
                          av_res_temp(:) = emax_not(elap,ipast,:,ipau,iedu)
                          v_slope_p = (av_res_temp(2)-av_res_temp(1))/(wealth(2) - wealth(1))
                          betanornew(t,imun,ipast,ipau,iedu,elap,Nwealth) = av_res_temp(Nwealth)
                          DO iwealth = Nwealth-1, 1, -1
                             IF (av_res_temp(iwealth+1) - av_res_temp(iwealth) > small_no) THEN
                                betanornew(t,imun,ipast,ipau,iedu,elap,iwealth) = av_res_temp(iwealth)
                                V_slope = (av_res_temp(iwealth+1)-av_res_temp(iwealth))/(wealth(iwealth+1) - wealth(iwealth))
                             ELSE        
                                V_slope = inc_slope*V_slope_p+V_slope_p
                                betanornew(t,imun,ipast,ipau,iedu,elap,iwealth) = V_slope*(wealth(iwealth) - wealth(iwealth+1)) + betanornew(t,imun,ipast,ipau,iedu,elap,iwealth+1)
                             END IF
                             V_slope_p = V_slope
                          END DO
                       ELSE
                          betanornew(t,imun,ipast,ipau,iedu,elap,:) = emax_not(elap,ipast,:,ipau,iedu)
                       END IF
                       
                    END DO
                 END DO
              END DO
           END DO
           
           ! Compute the value function of an individual that enters t as mayor MAX(emax,emaxnor)
           ! We use the same subroutine (vfunapprox_Tend) for all periods (Tend and earlier periods 
           ! Aproximating the max  value function

           IF (t == Tend) flag_Tend = 1

           loop_vf1 = Neduc*Npaudits*(Nnterms-1)*Npast*Nelap
           ntasks_vf1 = INT(loop_vf1/nprocs_t)
           restasks_vf1 = loop_vf1 - ntasks_vf1*nprocs_t
           
           ALLOCATE(emax_est_temp(Nab,Nwealth,Nsteal,Nq), temp_vfun(MMability_steal_q))
           temp_vfun = 0d0
                      
           counter_vf1 = 0d0
           DO iedu = 1, Neduc
              DO ipau = 1, Npaudits
                 DO iterm = 2, Nnterms
                    DO ipast = 1, Npast
                       DO elap = 1, Nelap

                          count_steal = 0
                          count_q = 0
                          emax_est_temp = 0d0
                          DO iwealth = 1, Nwealth
                             DO ia = 1, Nab
                                DO iq = 1, Nq
                                   DO isteal = 1, Nsteal
                                      
                                      emax_est_temp(ia,iwealth,isteal,iq) = emax_est(elap,ipast,iterm,iwealth,ipau,ia,iedu,isteal,iq)
                                      IF (isteal > 1) THEN
                                         IF (ABS(emax_est_temp(ia,iwealth,isteal,iq)-emax_est_temp(ia,iwealth,isteal-1,iq)) > thres_count) count_steal = count_steal + 1
                                      END IF
                                      IF (iq > 1) THEN
                                         IF (ABS(emax_est_temp(ia,iwealth,isteal,iq)-emax_est_temp(ia,iwealth,isteal,iq-1)) > thres_count) count_q = count_q + 1
                                      END IF
                                      
                                   END DO
                                END DO
                             END DO
                          END DO

                          counter_vf1 = counter_vf1 + 1
                          IF ((counter_vf1 <= ntasks_vf1*nprocs_t .AND. counter_vf1 >= myrank_t*ntasks_vf1+1 .AND. &
                               counter_vf1 <= myrank_t*ntasks_vf1+ntasks_vf1) .OR. &
                               (counter_vf1 > ntasks_vf1*nprocs_t .AND. counter_vf1 - ntasks_vf1*nprocs_t-1 == myrank_t)) THEN
                             
                             
                             IF (count_q < 21 .AND. count_steal < 21) THEN
                                CALL vfunapprox_ability(emax_est_temp(:,:,1,1),temp_vfun(:))
                             ELSE IF (count_q >= 21 .AND. count_steal < 21) THEN
                                CALL vfunapprox_ability_q(emax_est_temp(:,:,1,:),temp_vfun(:))
                             ELSE IF (count_q < 21 .AND. count_steal >= 21) THEN
                                CALL vfunapprox_ability_steal(emax_est_temp(:,:,:,1),temp_vfun(:))
                             ELSE
                                CALL vfunapprox_ability_steal_q(emax_est_temp(:,:,:,:),temp_vfun(:))
                             END IF
                             betanewrt(ipast,iterm,ipau,iedu,elap,:) = temp_vfun(:)
                             
!!$                       write(*,'(a,4i5,16f12.7)') 'betanewrt',ipast,iterm,ipau,iedu, betanewrt(ipast,iterm,ipau,iedu,:)
!!$                       write(*,*) ''
                          
!!$                       flag_here = 0
                          
                          END IF

                       END DO
                    END DO
                 END DO
              END DO
           END DO

           flag_Tend = 0

           DEALLOCATE(emax_est_temp,temp_vfun)

           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN

              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
              CALL MPI_ALLREDUCE(betanewrt(1,1,1,1,1,1), betanewrtt(1,1,1,1,1,1), Npast*Nnterms*Npaudits*Neduc*Nelap*MMability_steal_q, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(betanewrt(1,1,1,1,1,1), betanewrtt(1,1,1,1,1,1), Npast*Nnterms*Npaudits*Neduc*Nelap*MMability_steal_q, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

           END IF
           DEALLOCATE(betanewrt)
           
           DO iedu = 1, Neduc
              DO ipau = 1, Npaudits
                 DO iterm = 2, Nnterms
                    DO ipast = 1, Npast
                       DO elap = 1, Nelap

                          betanewcr(t,imun,ipast,iterm,ipau,iedu,elap,:) = betanewrtt(ipast,iterm,ipau,iedu,elap,:)

                       END DO
                    END DO
                 END DO
              END DO
           END DO

           DEALLOCATE(emax_run,emax_not,emax_est)

!!$           CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)

           !3. Compute the value of an individual who was a mayor two periods or more ago 
           !and lives in a period in which the election this period is won by the incumbent           
8834       DEALLOCATE(betanewrtt)
           IF (jj == 2) THEN
              IF (t > Retage) THEN
                 DEALLOCATE(utilt, emax_runt, ptempt_run, betanewrt)
              ELSE IF (t == Retage) THEN
                 DEALLOCATE(utilt)
              END IF
           END IF
           
           ALLOCATE(emaxpmayort(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           emaxpmayort = 0d0
           !Reset ptemp to 0.0 to evaluate that the probabilities add up to 1
           ALLOCATE(ptemppmayort(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           ptemppmayort = 0d0
           
           counter2 = 0
           DO iedu = 1, Neduc
              !The probability of being audited may differ across terms
              DO ipau = 1, Npaudits
                 !Net Wealth
                 DO iwealth = 1, Nwealth
                    DO ipast = 1, Npast_t
                          
                       !The following variables belong to the current incumbent and not the past mayor we consider
                       !They are important because they determine the expected utility of public consumption produced by the challenger
                       !Those variables are state variables to determine that object
                       !Past history of this mayor: ipast is about what happened in all periods
                       DO elap = 1, Nelap
                          DO iwealthi = 1, Nwealth
                             DO iedui = 1, Neduc
                                DO ipasti = 1, Npast
                                   DO agei = 1, agen
                                      
                                      
                                      counter2 = counter2 + 1
                                      IF ((counter2 <= ntasks2*nprocs_t .AND. counter2 >= myrank_t*ntasks2+1 .AND. counter2 <= myrank_t*ntasks2+ntasks2) .OR. &
                                           (counter2 > ntasks2*nprocs_t .AND. counter2 - ntasks2*nprocs_t - 1 == myrank_t)) THEN
                                         
                                         ! The incumbent must be in term > 1
                                         DO itermi = 2, Nnterms
                                            DO iq = 1, Nq
                                               DO isteal = 1, Nsteal

                                                  emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)*SUM(probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,:,:,:))
                                                  
                                                  ptemppmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = ptemppmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + SUM(probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,:,:,:))

!!$                                                  if (t>=4 .and. elap==1 .and. (itermi==1 .or. itermi==2) .and. isteal==1 .and. iq==1 .and. iwealthi==5 .and. ipau==1 .and. ipasti==1 .and. iedui==1 .and. ipast==1 .and. iwealth==4 .and. iedu==1) WRITE(*,'(a,12i5,3f20.10)') 'emaxpmayor_i', itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq,emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
                                                  
!!$                                                  if (t== 7 .AND. itermi==3 .AND. agei==1 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==2 .AND. ipau==1 .AND. iedu==1 .AND. elap==2 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,1i4,3f20.10)') 'emaxpmayor_i', iq, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
                                                  
!!$                                                  IF (t >= 5)  THEN
!!$                                                     if (itermi==2 .AND. agei==2 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==1 .AND. ipau==1 .AND. iedu==2 .AND. elap==1 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,1i4,3f20.10)') 'emaxpmayor_i', iq, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
!!$                                                  END IF

!!$                                                  IF (myrank_t == 0 .and. jj == 2 .and. t <= 3 .and. itermi == 2 .and. ipasti == 2 .and. iedui == 1 .and. ipast == 1 .and. iwealthi == 1 .and. ipau == 1 .and. iedu == 1 .and. elap == 1) write(*,'(a,4i4,3f20.10)') 'emaxpmayor_i', iwealth, agei, iq, isteal, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
                                                  
!!$                                                  IF (myrank_t == 0 .and. jj == 2 .and. t >= 6) write(*,'(a,2i4,3f20.10)') 'emaxpmayor_i', iq, isteal, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_i(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), probemax3(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)

                                               END DO
                                            END DO
                                         END DO
                                         
                                      END IF

                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           
!!$           IF (myrank_t == 0) WRITE(*,*) 'end loop 3'

           ALLOCATE(emaxpmayornor(Nelap,Npast_t,Nwealth,Npaudits,Neduc))
           emaxpmayornor = 0d0

           !4. Compute the value of an individual who was a mayor two periods or more ago 
           !and lives in a period in which the election this period is won by the challenger
           counter3 = 0           
           DO iedu = 1, Neduc       
              ! Variables that chacaracterie the past mayor
              ! The probability of being audited may differ across terms
              DO ipau = 1, Npaudits
                 !Net Wealth
                 DO iwealth = 1, Nwealth
                    DO ipast = 1, Npast_t
                       DO elap = 1, Nelap

                          DO iwealthi = 1, Nwealth
                             
                             ! We don't need the characteristics of the challenger because we only need the expected log of qcons                       
                             counter3 = counter3 + 1
                             IF ((counter3 <= ntasks3*nprocs_t .AND. counter3 >= myrank_t*ntasks3+1 .AND. counter3 <= myrank_t*ntasks3+ntasks3) .OR. &
                                  (counter3 > ntasks3*nprocs_t .AND. counter3 - ntasks3*nprocs_t - 1 == myrank_t)) THEN
                                
                                DO iedui = 1, Neduc
                                   DO ipasti = 1, Npast
                                      DO agei = 1, ageN
                                         DO itermi = 2, Nnterms
                                            DO iq = 1, Nq
                                               DO isteal = 1, Nsteal
                                                  
                                                  ! Challenger's observable characteristics
                                                  DO iwealthc = 1, Nwealth
                                                     DO ieduc = 1, Neduc
                                                        DO agec = 1, agen
                                                           
                                                           emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + vemax_voter_c_all(agec,iwealthc,ieduc,elap,ipast,iwealth,ipau,iedu) * probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
                                                           
                                                           ptemppmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = ptemppmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) + probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)

!!$                                                  if (t>=4 .and. elap==1 .and. (itermi==1 .or. itermi==2) .and. isteal==1 .and. iq==1 .and. iwealthi==5 .and. ipau==1 .and. ipasti==1 .and. iedui==1 .and. ipast==1 .and. iwealth==4 .and. iedu==1) WRITE(*,'(a,12i5,3f20.10)') 'emaxpmayor_c', itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_c(elap,ipast,iwealth,ipau,iedu), probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
                                                  
!!$                                                  IF (t >= 5)  THEN
!!$                                                     if (itermi==2 .AND. agei==2 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==1 .AND. ipau==1 .AND. iedu==2 .AND. elap==1 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,1i4,3f20.10)') 'emaxpmayor_c', iq, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_c(elap,ipast,iwealth,ipau,iedu), probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)
!!$                                                  END IF

!!$                                                  if (t== 7 .AND. itermi==3 .AND. agei==1 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==2 .AND. ipau==1 .AND. iedu==1 .AND. elap==2 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,1i4,3f20.10)') 'emaxpmayor_c', iq, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_c(elap,ipast,iwealth,ipau,iedu), probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)

!!$                                                  IF (myrank_t == 0 .and. jj == 2 .and. t <= 3 .and. itermi == 2 .and. ipasti == 2 .and. iedui == 1 .and. ipast == 1 .and. iwealthi == 1 .and. ipau == 1 .and. iedu == 1 .and. elap == 1) write(*,'(a,4i4,3f20.10)') 'emaxpmayor_c', iwealth, agei, iq, isteal, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_c(elap,ipast,iwealth,ipau,iedu), probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)

!!$                                                  IF (myrank_t == 0 .and. jj == 2 .and. t >= 6) write(*,'(a,2i4,3f20.10)') 'emaxpmayor_c', iq, isteal, emaxpmayort(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), vemax_voter_c(elap,ipast,iwealth,ipau,iedu), probemax4(agei,iedui,itermi-1,ipasti,ipau,iwealthi,isteal,iq,elap,agec,ieduc,iwealthc)

                                                        END DO
                                                     END DO
                                                  END DO       
                                               END DO
                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO

                             END IF

                                
                          END DO
                                      
!!$                             emaxpmayornort(elap,ipast,iwealth,ipau,iedu) = emaxpmayornort(elap,ipast,iwealth,ipau,iedu) + vemax_voter_c(elap,ipast,iwealth,ipau,iedu)
                          
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           emaxpmayornor = vemax_voter_c
           
           ALLOCATE(emaxpmayor(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           emaxpmayor = 0d0
           ALLOCATE(ptemppmayor(Nnterms,agen,Npast,Neduc,Nwealth,Nelap,Npast_t,Nwealth,Npaudits,Neduc,Nsteal,Nq))
           ptemppmayor = 0d0


           IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
              
              CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)                      
              CALL MPI_ALLREDUCE(emaxpmayort(1,1,1,1,1,1,1,1,1,1,1,1),emaxpmayor(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq,MPI_REAL8,MPI_SUM,MPI_COMM_WORLD,ierr)                      
              CALL MPI_ALLREDUCE(ptemppmayort(1,1,1,1,1,1,1,1,1,1,1,1),ptemppmayor(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq,MPI_REAL8,MPI_SUM,MPI_COMM_WORLD,ierr)           
!!$              CALL MPI_ALLREDUCE(emaxpmayornort(1,1,1,1,1), emaxpmayornor(1,1,1,1,1), Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, MPI_COMM_WORLD, ierr)

           ELSE

              CALL MPI_BARRIER(NEW_COMM, ierr)
              CALL MPI_ALLREDUCE(emaxpmayort(1,1,1,1,1,1,1,1,1,1,1,1),emaxpmayor(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq,MPI_REAL8,MPI_SUM,NEW_COMM,ierr)
              CALL MPI_ALLREDUCE(ptemppmayort(1,1,1,1,1,1,1,1,1,1,1,1),ptemppmayor(1,1,1,1,1,1,1,1,1,1,1,1),Nnterms*agen*Npast*Neduc*Nwealth*Nelap*Npast_t*Nwealth*Npaudits*Neduc*Nsteal*Nq,MPI_REAL8,MPI_SUM,NEW_COMM,ierr)
!!$              CALL MPI_ALLREDUCE(emaxpmayornort(1,1,1,1,1), emaxpmayornor(1,1,1,1,1), Nelap*Npast_t*Nwealth*Npaudits*Neduc, MPI_REAL8, MPI_SUM, NEW_COMM, ierr)

           END IF
           DEALLOCATE(emaxpmayort)
           DEALLOCATE(ptemppmayort)
           
           !Check the probabilities add up to 1
           DO iedu = 1, Neduc       
              DO ipau = 1, Npaudits
                 DO iwealth = 1, Nwealth
                    DO ipast = 1, Npast_t
                       DO elap = 1, Nelap
                          DO iwealthi = 1, Nwealth
                             DO iedui = 1, Neduc
                                DO ipasti = 1, Npast
                                   DO agei = 1, ageN
                                      DO itermi = 2, Nnterms
                                         DO iq = 1, Nq
                                            DO isteal = 1, Nsteal
                                               
                                               IF (ptemppmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) < 0.99d0 .OR. ptemppmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) > 1.001d0) THEN
                                                  IF (myrank_t == 0) WRITE(*,'(a,1f14.8,12I3)') 'wrong prob pmayor 2', ptemppmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq
                                               END IF

                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO
           DEALLOCATE(ptemppmayor)
           
           !In this loop we take into account that an incumbent may decide not to run
           DO iedui = 1, Neduc
              DO ipau = 1, Npaudits
                 DO iwealthi = 1, Nwealth                       
                    DO itermi = 2, Nnterms
                       DO ipasti = 1, Npast
                          DO agei = 1, ageN
                             DO iedu = 1, Neduc       
                                DO ipast = 1, Npast_t
                                   DO iwealth = 1, Nwealth
                                      DO elap = 1, Nelap
                                         DO isteal = 1, Nsteal
                                            DO iq = 1, Nq

!!$                                               if (t>=4 .and. elap==1 .and. (itermi==1 .or. itermi==2) .and. isteal==1 .and. iq==1 .and. iwealthi==5 .and. ipau==1 .and. ipasti==1 .and. iedui==1 .and. ipast==1 .and. iwealth==4 .and. iedu==1) WRITE(*,'(a,12i5,3f20.10)') 'emaxpmayor run', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), emaxpmayornor(elap,ipast,iwealth,ipau,iedu), pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
                                               
!!$                                               if (t == 7) write(*,'(a,12i4,3f20.10)') 'emaxpmayor run b', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), emaxpmayornor(elap,ipast,iwealth,ipau,iedu), pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
                                               
!!$                                               IF (myrank_t == 0 .and. jj == 2 .and. t <= 3 .and. itermi == 2 .and. ipasti == 2 .and. iedui == 1 .and. ipast == 1 .and. iwealthi == 1 .and. ipau == 1 .and. iedu == 1 .and. elap == 1) write(*,'(a,5i4,3f20.10)') 'emaxpmayor run b', t,agei,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), emaxpmayornor(elap,ipast,iwealth,ipau,iedu), pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)

!!$                                               IF (myrank_t == 0 .and. t == 5) THEN
!!$                                                  if (itermi==2 .AND. agei==2 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==1 .AND. ipau==1 .AND. iedu==2 .AND. elap==1 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,12i4,3f20.10)') 'emaxpmayor run b', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), emaxpmayornor(elap,ipast,iwealth,ipau,iedu), pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
!!$                                               END IF

!!$                                               if (t== 7 .AND. itermi==3 .AND. agei==1 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==2 .AND. ipau==1 .AND. iedu==1 .AND. elap==2 .AND. iwealth==1 .AND. isteal==1) write(*,'(a,12i4,3f20.10)') 'emaxpmayor run b', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq), emaxpmayornor(elap,ipast,iwealth,ipau,iedu), pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq)
                                               
                                               emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq) = &
                                                    emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)*pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq) + &
                                                    emaxpmayornor(elap,ipast,iwealth,ipau,iedu)*(1d0-pr_run(agemayor(agei),imun,ipasti,itermi,iwealthi,ipau,iedui,isteal,iq))

!!$                                               IF (myrank_t == 0 .and. t == 7) write(*,'(a,12i4,3f20.10)') 'emaxpmayor run a', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap,iwealth,isteal,iq, emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)

                                            END DO
                                         END DO
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO
           END DO

           IF (jj == 1 .AND. t >= 6) THEN

              IF (t == Tend) flag_Tend = 1

              !Dynamic Allocation for the size of the betas conditional on current age of mayor!
              ! We use Tend instead of ageN to have all the possible cells
              ALLOCATE(betapmayort1(Nnterms,Tend,Npast,Neduc,Npast_t,Nwealth,Npaudits,Neduc,Nelap,MMsteal_q),&
                       betapmayortt1(Nnterms,Tend,Npast,Neduc,Npast_t,Nwealth,Npaudits,Neduc,Nelap,MMsteal_q))
              betapmayort1 = 0d0
              betapmayortt1 = 0d0
              ALLOCATE(emaxpmayortemp1(Nwealth,Nsteal,Nq))
              emaxpmayortemp1 = 0d0
              loop_vf3 = Neduc*Npaudits*Nwealth*Npast_t*Neduc*Npast*ageN*(Nnterms-1)*Nelap
              ALLOCATE(temp_vfun(MMsteal_q))
              temp_vfun = 0d0
              
              ntasks_vf3 = INT(loop_vf3/nprocs_t)
              restasks_vf3 = loop_vf3 - ntasks_vf3*nprocs_t
              
              counter_vf3 = 0
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iwealthi = 1, Nwealth
                       DO ipast = 1, Npast_t
                          DO iedui = 1, Neduc
                             DO ipasti = 1, Npast
                                DO agei = 1, ageN
                                   DO itermi = 2, Nnterms
                                      DO elap = 1, Nelap

!!$                                         if (t == 6 .AND. myrank_t == 1 .AND. itermi==2 .AND. agei==2 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==1 .AND. ipau==1 .AND. iedu==2 .AND. elap==1) flag_here = 890
!!$                                         if (t== 7 .AND. itermi==3 .AND. agei==1 .AND. ipasti==1 .AND. iedui==1 .AND. iwealthi==1 .AND. ipast==2 .AND. ipau==1 .AND. iedu==1 .AND. elap==2)  flag_here = 890

                                         count_steal = 0
                                         count_q = 0
                                         emaxpmayortemp1 = 0d0
                                         ! The approximation is over the wealth of the past mayor and not of the incumbent
                                         DO iwealth = 1, Nwealth                                         
                                            DO iq = 1, Nq
                                               DO isteal = 1, Nsteal
                                                  
                                                  emaxpmayortemp1(iwealth,isteal,iq) = emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)
                                                  IF (isteal > 1) THEN
                                                     IF (ABS(emaxpmayortemp1(iwealth,isteal,iq)-emaxpmayortemp1(iwealth,isteal-1,iq)) > thres_count) count_steal = count_steal + 1
                                                  END IF
                                                  IF (iq > 1) THEN
                                                     IF (ABS(emaxpmayortemp1(iwealth,isteal,iq)-emaxpmayortemp1(iwealth,isteal,iq-1)) > thres_count) count_q = count_q + 1
                                                  END IF

!!$                                                  IF (flag_here == 890) write(*,'(a,9i4,2f20.10)') 'betapmayort1', itermi,agei,ipasti,iedui,iwealthi,ipast,ipau,iedu,elap, emaxpmayortemp1(iwealth,isteal,iq), emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)
                                                  
                                               END DO
                                            END DO
                                         END DO

                                         counter_vf3 = counter_vf3 + 1
                                         IF ((counter_vf3 <= ntasks_vf3*nprocs_t .AND. counter_vf3 >= myrank_t*ntasks_vf3+1 .AND. &
                                              counter_vf3 <= myrank_t*ntasks_vf3+ntasks_vf3) .OR. &
                                              (counter_vf3 > ntasks_vf3*nprocs_t .AND. counter_vf3 - ntasks_vf3*nprocs_t-1 == myrank_t)) THEN

                                            IF (count_q < 21 .AND. count_steal < 21) THEN
                                               IF (t == Tend) THEN
                                                  av_res_temp(:) = emaxpmayortemp1(:,1,1)
                                                  v_slope_p = (av_res_temp(2)-av_res_temp(1))/(wealth(2) - wealth(1))
                                                  betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,Nwealth) = av_res_temp(Nwealth)
                                                  DO iwealth = Nwealth-1, 1, -1
                                                     IF (av_res_temp(iwealth+1) - av_res_temp(iwealth) > small_no) THEN
                                                        betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,iwealth) = av_res_temp(iwealth)
                                                        V_slope = (av_res_temp(iwealth+1)-av_res_temp(iwealth))/(wealth(iwealth+1) - wealth(iwealth))
                                                     ELSE        
                                                        V_slope = inc_slope*V_slope_p+V_slope_p
                                                        betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,iwealth) = V_slope*(wealth(iwealth) - wealth(iwealth+1)) + &
                                                        betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,iwealth+1)
                                                     END IF
                                                     V_slope_p = V_slope
                                                  END DO
                                               ELSE                                                  
                                                  betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,1:Nwealth) = emaxpmayortemp1(:,1,1)
                                               END IF
                                            ELSE IF (count_q >= 21 .AND. count_steal < 21) THEN
                                               CALL vfunapprox_q(emaxpmayortemp1(:,1,:),temp_vfun(:))
                                               betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = temp_vfun(:)
                                            ELSE IF (count_q < 21 .AND. count_steal >= 21) THEN
                                               CALL vfunapprox_steal(emaxpmayortemp1(:,:,1),temp_vfun(:))
                                               betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = temp_vfun(:)
                                            ELSE
                                               CALL vfunapprox_steal_q(emaxpmayortemp1(:,:,:),temp_vfun(:))
                                               betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = temp_vfun(:)
                                            END IF

!!$                                            IF (flag_here == 890) write(*,'(a,12i4,15f14.8)') 'betapmayort1 1', count_q, count_steal, ipasti, itermi,agei,ipasti,iedui,iwealthi,elap,ipast,ipau,iedu, betapmayort1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:)
                                            
                                         END IF

                                         flag_here = 0
                                         
                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

              flag_Tend = 0

              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN

                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
                 CALL MPI_ALLREDUCE(betapmayort1(1,1,1,1,1,1,1,1,1,1), betapmayortt1(1,1,1,1,1,1,1,1,1,1), Nnterms*Tend*Npast*Neduc*Npast_t*Nwealth*Npaudits*Neduc*Nelap*MMsteal_q,MPI_REAL8,MPI_SUM,MPI_COMM_WORLD, ierr)

              ELSE

                 CALL MPI_BARRIER(NEW_COMM, ierr)
                 CALL MPI_ALLREDUCE(betapmayort1(1,1,1,1,1,1,1,1,1,1), betapmayortt1(1,1,1,1,1,1,1,1,1,1), Nnterms*Tend*Npast*Neduc*Npast_t*Nwealth*Npaudits*Neduc*Nelap*MMsteal_q,MPI_REAL8,MPI_SUM,NEW_COMM, ierr)

              END IF
              DEALLOCATE(betapmayort1)
              
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iwealthi = 1, Nwealth
                       DO ipast = 1, Npast_t
                          DO iedui = 1, Neduc
                             DO ipasti = 1, Npast
                                DO agei = 1, ageN
                                   DO itermi = 2, Nnterms
                                      DO elap = 1, Nelap

                                         betapmayortemp1(t,imun,itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = betapmayortt1(itermi,agemayor(agei),ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:)

                                      END DO
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

              DEALLOCATE(betapmayortt1, emaxpmayortemp1, temp_vfun)
              
           ELSE

              IF (t == Tend) flag_Tend = 1

              ALLOCATE(betapmayort2(Nnterms,Npast,Neduc,Npast_t,Nwealth,Npaudits,Neduc,Nelap,MMage_steal_q),betapmayortt2(Nnterms,Npast,Neduc,Npast_t,Nwealth,Npaudits,Neduc,Nelap,MMage_steal_q))
              betapmayort2 = 0d0
              betapmayortt2 = 0d0
              ALLOCATE(emaxpmayortemp2(Nwealth,agen,Nsteal,Nq))
              emaxpmayortemp2 = 0d0
              ALLOCATE(temp_vfun(MMage_steal_q))
              temp_vfun = 0d0

              loop_vf3 = Neduc*Npaudits*Nwealth*Npast_t*Neduc*Npast*(Nnterms-1)*Nelap
              ntasks_vf3 = INT(loop_vf3/nprocs_t)
              restasks_vf3 = loop_vf3 - ntasks_vf3*nprocs_t

              counter_vf3 = 0d0
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iwealthi = 1, Nwealth
                       DO ipast = 1, Npast_t
                          DO iedui = 1, Neduc
                             DO ipasti = 1, Npast
                                DO itermi = 2, Nnterms
                                   DO elap = 1, Nelap
                                      
                                      count_steal = 0
                                      count_q = 0
                                      emaxpmayortemp2 = 0d0
                                      ! The approximation is over the wealth of the past mayor and not of the incumbent
                                      DO agei = 1, ageN
                                         DO iwealth = 1, Nwealth
                                            DO iq = 1, Nq                                                                                           
                                               DO isteal = 1, Nsteal
                                                  
                                                  emaxpmayortemp2(iwealth,agei,isteal,iq) = emaxpmayor(itermi,agei,ipasti,iedui,iwealthi,elap,ipast,iwealth,ipau,iedu,isteal,iq)
                                                  IF (isteal > 1) THEN
                                                     IF (ABS(emaxpmayortemp2(iwealth,agei,isteal,iq)-emaxpmayortemp2(iwealth,agei,isteal-1,iq)) > thres_count) count_steal = count_steal + 1
                                                  END IF
                                                  IF (iq > 1) THEN
                                                     IF (ABS(emaxpmayortemp2(iwealth,agei,isteal,iq)-emaxpmayortemp2(iwealth,agei,isteal,iq-1)) > thres_count) count_q = count_q + 1
                                                  END IF
                                                  
                                               END DO
                                            END DO
                                         END DO
                                      END DO

                                      counter_vf3 = counter_vf3 + 1
                                      IF ((counter_vf3 <= ntasks_vf3*nprocs_t .AND. counter_vf3 >= myrank_t*ntasks_vf3+1 .AND. &
                                           counter_vf3 <= myrank_t*ntasks_vf3+ntasks_vf3) .OR. &
                                           (counter_vf3 > ntasks_vf3*nprocs_t .AND. counter_vf3 - ntasks_vf3*nprocs_t-1 == myrank_t)) THEN
                                         
                                         IF (count_q < 21 .AND. count_steal < 21) THEN
                                            CALL vfunapprox_age(agen,agemayor(:),emaxpmayortemp2(:,:,1,1),temp_vfun(:))
                                         ELSE IF (count_q >= 21 .AND. count_steal < 21) THEN
                                            CALL vfunapprox_age_q(agen,agemayor(:),emaxpmayortemp2(:,:,1,:),temp_vfun(:))
                                         ELSE IF (count_q < 21 .AND. count_steal >= 21) THEN
                                            CALL vfunapprox_age_steal(agen,agemayor(:),emaxpmayortemp2(:,:,:,1),temp_vfun(:))
                                         ELSE
                                            CALL vfunapprox_age_steal_q(agen,agemayor(:),emaxpmayortemp2(:,:,:,:),temp_vfun(:))
                                         END IF
                                         betapmayort2(itermi,ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = temp_vfun(:)

!!$                                         if (jj == 2 .and. t <= 10 .and. myrank_t == 0) write(*,'(a,10i5,15f14.7)') 'betapmayor check', count_q, count_steal, itermi,ipasti,iedui,ipast,iwealthi,ipau,iedu,elap, betapmayort2(itermi,ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:)

                                      END IF
                                      
                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

              flag_Tend = 0

              IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN

                 CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
                 CALL MPI_ALLREDUCE(betapmayort2(1,1,1,1,1,1,1,1,1), betapmayortt2(1,1,1,1,1,1,1,1,1), Nnterms*Npast*Neduc*Npast_t*Nwealth*Npaudits*Neduc*Nelap*MMage_steal_q,MPI_REAL8,MPI_SUM, MPI_COMM_WORLD, ierr)
                 
              ELSE

                 CALL MPI_BARRIER(NEW_COMM, ierr)
                 CALL MPI_ALLREDUCE(betapmayort2(1,1,1,1,1,1,1,1,1), betapmayortt2(1,1,1,1,1,1,1,1,1), Nnterms*Npast*Neduc*Npast_t*Nwealth*Npaudits*Neduc*Nelap*MMage_steal_q,MPI_REAL8,MPI_SUM, NEW_COMM, ierr)

              END IF                 
              DEALLOCATE(betapmayort2)
              
              DO iedu = 1, Neduc       
                 DO ipau = 1, Npaudits
                    DO iwealthi = 1, Nwealth
                       DO ipast = 1, Npast_t
                          DO iedui = 1, Neduc
                             DO ipasti = 1, Npast
                                DO itermi = 2, Nnterms
                                   DO elap = 1, Nelap

                                      betapmayor(t,imun,itermi,ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:) = betapmayortt2(itermi,ipasti,iedui,ipast,iwealthi,ipau,iedu,elap,:)

                                   END DO
                                END DO
                             END DO
                          END DO
                       END DO
                    END DO
                 END DO
              END DO

              DEALLOCATE(betapmayortt2, emaxpmayortemp2, temp_vfun)
              
           END IF

           DO iedu = 1, Neduc 
              DO ipau = 1, Npaudits
                 DO ipast = 1, Npast_t
                    DO elap = 1, Nelap

                       IF (t == Tend) THEN
                          av_res_temp(:) = emaxpmayornor(elap,ipast,:,ipau,iedu)
                          v_slope_p = (av_res_temp(2)-av_res_temp(1))/(wealth(2) - wealth(1))
                          betapmayornor(t,imun,ipast,ipau,iedu,elap,Nwealth) = av_res_temp(Nwealth)
                          DO iwealth = Nwealth-1, 1, -1
                             IF (av_res_temp(iwealth+1) - av_res_temp(iwealth) > small_no) THEN
                                betapmayornor(t,imun,ipast,ipau,iedu,elap,iwealth) = av_res_temp(iwealth)
                                V_slope = (av_res_temp(iwealth+1)-av_res_temp(iwealth))/(wealth(iwealth+1) - wealth(iwealth))
                             ELSE        
                                V_slope = inc_slope*V_slope_p+V_slope_p
                                betapmayornor(t,imun,ipast,ipau,iedu,elap,iwealth) = V_slope*(wealth(iwealth) - wealth(iwealth+1)) + betapmayornor(t,imun,ipast,ipau,iedu,elap,iwealth+1)
                             END IF
                             V_slope_p = V_slope
                          END DO
                       ELSE
                          betapmayornor(t,imun,ipast,ipau,iedu,elap,:) = emaxpmayornor(elap,ipast,:,ipau,iedu)
                       END IF

                    END DO
                 END DO
              END DO
           END DO

           DEALLOCATE(emaxpmayor, emaxpmayornor)
           DEALLOCATE(qconsf, stealf, newsavf, vemaxt)           
           DEALLOCATE(probemax1,probemax2,probemax3,probemax4,probqcons_c,probqcons_i)
           DEALLOCATE(ELNqconsout_i,ELNqconsout_i_1)
           DEALLOCATE(vemax_voter_i, vemax_voter_c, vemax_voter_c_all, temp_prob_c, temp_prob_c_all)
           IF(ALLOCATED(pqtemp_i)) DEALLOCATE(pqtemp_i)

        END DO
        
        CALL cpu_time(t2)
        if (myrank_t == 0 .AND. flag_policy_evaluation == 0) write(*,*) 'time for period', t, t2-t1
        DEALLOCATE(agemayor)

        IF (t == Tend) flag_Tend = 0

     END DO

     DEALLOCATE(vemax_voter_i_age)
     DEALLOCATE(vemax_voter_c_age, vemax_voter_c_age_all)
     DEALLOCATE(pr_run)

     DEALLOCATE(Pr_i_win)

     IF (flag_policy_evaluation == 0 .OR. (flag_policy_evaluation == 1 .AND. flag_optimal_auditprob == 1)) THEN
        CALL MPI_BARRIER(MPI_COMM_WORLD, ierr)
     ELSE
        CALL MPI_BARRIER(NEW_COMM, ierr)
     END IF

     if (myrank_t == 0 .AND. flag_policy_evaluation == 0) write(*,*) 'end of emaxfun loop', jj
     
  END DO

  DEALLOCATE(qconsout, stealout, newsavout)

END SUBROUTINE emaxfun
